From a68d20733b40d855a811eea215c2c422aa34eccf Mon Sep 17 00:00:00 2001 From: ohmayr Date: Thu, 15 Jan 2026 19:52:50 +0000 Subject: [PATCH 1/5] chore: use ruff based code formatting --- .generator/cli.py | 110 +- .generator/requirements.in | 3 +- .librarian/generate-request.json | 40 + packages/google-cloud-vision/docs/conf.py | 10 +- .../google/cloud/vision/__init__.py | 362 +- .../google/cloud/vision_v1/__init__.py | 439 +- .../services/image_annotator/__init__.py | 6 +- .../services/image_annotator/async_client.py | 263 +- .../services/image_annotator/client.py | 446 +- .../image_annotator/transports/__init__.py | 20 +- .../image_annotator/transports/base.py | 142 +- .../image_annotator/transports/grpc.py | 164 +- .../transports/grpc_asyncio.py | 174 +- .../image_annotator/transports/rest.py | 803 +- .../image_annotator/transports/rest_base.py | 318 +- .../services/product_search/__init__.py | 6 +- .../services/product_search/async_client.py | 978 +- .../services/product_search/client.py | 1118 +-- .../services/product_search/pagers.py | 268 +- .../product_search/transports/__init__.py | 20 +- .../product_search/transports/base.py | 366 +- .../product_search/transports/grpc.py | 515 +- .../product_search/transports/grpc_asyncio.py | 550 +- .../product_search/transports/rest.py | 2585 ++---- .../product_search/transports/rest_base.py | 792 +- .../google/cloud/vision_v1/types/__init__.py | 195 +- .../google/cloud/vision_v1/types/geometry.py | 19 +- .../cloud/vision_v1/types/image_annotator.py | 352 +- .../cloud/vision_v1/types/product_search.py | 22 +- .../vision_v1/types/product_search_service.py | 128 +- .../cloud/vision_v1/types/text_annotation.py | 125 +- .../cloud/vision_v1/types/web_detection.py | 17 +- .../google/cloud/vision_v1p1beta1/__init__.py | 228 +- .../services/image_annotator/__init__.py | 6 +- .../services/image_annotator/async_client.py | 146 +- .../services/image_annotator/client.py | 291 +- .../image_annotator/transports/__init__.py | 20 +- .../image_annotator/transports/base.py | 98 +- .../image_annotator/transports/grpc.py | 105 +- .../transports/grpc_asyncio.py | 113 +- .../image_annotator/transports/rest.py | 198 +- .../image_annotator/transports/rest_base.py | 78 +- .../cloud/vision_v1p1beta1/types/__init__.py | 87 +- .../cloud/vision_v1p1beta1/types/geometry.py | 13 +- .../vision_v1p1beta1/types/image_annotator.py | 202 +- .../vision_v1p1beta1/types/text_annotation.py | 111 +- .../vision_v1p1beta1/types/web_detection.py | 17 +- .../google/cloud/vision_v1p2beta1/__init__.py | 275 +- .../services/image_annotator/__init__.py | 6 +- .../services/image_annotator/async_client.py | 182 +- .../services/image_annotator/client.py | 327 +- .../image_annotator/transports/__init__.py | 20 +- .../image_annotator/transports/base.py | 115 +- .../image_annotator/transports/grpc.py | 126 +- .../transports/grpc_asyncio.py | 135 +- .../image_annotator/transports/rest.py | 393 +- .../image_annotator/transports/rest_base.py | 120 +- .../cloud/vision_v1p2beta1/types/__init__.py | 112 +- .../cloud/vision_v1p2beta1/types/geometry.py | 19 +- .../vision_v1p2beta1/types/image_annotator.py | 279 +- .../vision_v1p2beta1/types/text_annotation.py | 125 +- .../vision_v1p2beta1/types/web_detection.py | 17 +- .../google/cloud/vision_v1p3beta1/__init__.py | 411 +- .../services/image_annotator/__init__.py | 6 +- .../services/image_annotator/async_client.py | 182 +- .../services/image_annotator/client.py | 367 +- .../image_annotator/transports/__init__.py | 20 +- .../image_annotator/transports/base.py | 118 +- .../image_annotator/transports/grpc.py | 126 +- .../transports/grpc_asyncio.py | 138 +- .../image_annotator/transports/rest.py | 393 +- .../image_annotator/transports/rest_base.py | 120 +- .../services/product_search/__init__.py | 6 +- .../services/product_search/async_client.py | 944 +- .../services/product_search/client.py | 1086 +-- .../services/product_search/pagers.py | 268 +- .../product_search/transports/__init__.py | 20 +- .../product_search/transports/base.py | 363 +- .../product_search/transports/grpc.py | 510 +- .../product_search/transports/grpc_asyncio.py | 553 +- .../product_search/transports/rest.py | 2359 ++--- .../product_search/transports/rest_base.py | 714 +- .../cloud/vision_v1p3beta1/types/__init__.py | 181 +- .../cloud/vision_v1p3beta1/types/geometry.py | 19 +- .../vision_v1p3beta1/types/image_annotator.py | 292 +- .../vision_v1p3beta1/types/product_search.py | 22 +- .../types/product_search_service.py | 116 +- .../vision_v1p3beta1/types/text_annotation.py | 125 +- .../vision_v1p3beta1/types/web_detection.py | 17 +- .../google/cloud/vision_v1p4beta1/__init__.py | 449 +- .../services/image_annotator/__init__.py | 6 +- .../services/image_annotator/async_client.py | 252 +- .../services/image_annotator/client.py | 433 +- .../image_annotator/transports/__init__.py | 20 +- .../image_annotator/transports/base.py | 154 +- .../image_annotator/transports/grpc.py | 161 +- .../transports/grpc_asyncio.py | 183 +- .../image_annotator/transports/rest.py | 696 +- .../image_annotator/transports/rest_base.py | 200 +- .../services/product_search/__init__.py | 6 +- .../services/product_search/async_client.py | 971 +- .../services/product_search/client.py | 1109 +-- .../services/product_search/pagers.py | 268 +- .../product_search/transports/__init__.py | 20 +- .../product_search/transports/base.py | 375 +- .../product_search/transports/grpc.py | 516 +- .../product_search/transports/grpc_asyncio.py | 560 +- .../product_search/transports/rest.py | 2482 ++--- .../product_search/transports/rest_base.py | 754 +- .../cloud/vision_v1p4beta1/types/__init__.py | 207 +- .../cloud/vision_v1p4beta1/types/face.py | 13 +- .../cloud/vision_v1p4beta1/types/geometry.py | 19 +- .../vision_v1p4beta1/types/image_annotator.py | 352 +- .../vision_v1p4beta1/types/product_search.py | 22 +- .../types/product_search_service.py | 128 +- .../vision_v1p4beta1/types/text_annotation.py | 125 +- .../vision_v1p4beta1/types/web_detection.py | 17 +- packages/google-cloud-vision/mypy.ini | 2 +- packages/google-cloud-vision/noxfile.py | 21 +- ...otator_async_batch_annotate_files_async.py | 4 +- ...notator_async_batch_annotate_files_sync.py | 4 +- ...tator_async_batch_annotate_images_async.py | 4 +- ...otator_async_batch_annotate_images_sync.py | 4 +- ...ge_annotator_batch_annotate_files_async.py | 4 +- ...age_annotator_batch_annotate_files_sync.py | 4 +- ...e_annotator_batch_annotate_images_async.py | 4 +- ...ge_annotator_batch_annotate_images_sync.py | 4 +- ...ted_product_search_create_product_async.py | 1 - ...product_search_create_product_set_async.py | 1 - ..._product_search_create_product_set_sync.py | 1 - ...ated_product_search_create_product_sync.py | 1 - ...uct_search_create_reference_image_async.py | 1 - ...duct_search_create_reference_image_sync.py | 1 - ...erated_product_search_get_product_async.py | 1 - ...ed_product_search_get_product_set_async.py | 1 - ...ted_product_search_get_product_set_sync.py | 1 - ...nerated_product_search_get_product_sync.py | 1 - ...roduct_search_get_reference_image_async.py | 1 - ...product_search_get_reference_image_sync.py | 1 - ...roduct_search_import_product_sets_async.py | 1 - ...product_search_import_product_sets_sync.py | 1 - ..._product_search_list_product_sets_async.py | 1 - ...d_product_search_list_product_sets_sync.py | 1 - ...ated_product_search_list_products_async.py | 1 - ...arch_list_products_in_product_set_async.py | 1 - ...earch_list_products_in_product_set_sync.py | 1 - ...rated_product_search_list_products_sync.py | 1 - ...duct_search_list_reference_images_async.py | 1 - ...oduct_search_list_reference_images_sync.py | 1 - ...ted_product_search_purge_products_async.py | 1 - ...ated_product_search_purge_products_sync.py | 1 - ...ted_product_search_update_product_async.py | 4 +- ...product_search_update_product_set_async.py | 4 +- ..._product_search_update_product_set_sync.py | 4 +- ...ated_product_search_update_product_sync.py | 4 +- ...e_annotator_batch_annotate_images_async.py | 4 +- ...ge_annotator_batch_annotate_images_sync.py | 4 +- ...otator_async_batch_annotate_files_async.py | 4 +- ...notator_async_batch_annotate_files_sync.py | 4 +- ...e_annotator_batch_annotate_images_async.py | 4 +- ...ge_annotator_batch_annotate_images_sync.py | 4 +- ...otator_async_batch_annotate_files_async.py | 4 +- ...notator_async_batch_annotate_files_sync.py | 4 +- ...e_annotator_batch_annotate_images_async.py | 4 +- ...ge_annotator_batch_annotate_images_sync.py | 4 +- ...ted_product_search_create_product_async.py | 1 - ...product_search_create_product_set_async.py | 1 - ..._product_search_create_product_set_sync.py | 1 - ...ated_product_search_create_product_sync.py | 1 - ...uct_search_create_reference_image_async.py | 1 - ...duct_search_create_reference_image_sync.py | 1 - ...erated_product_search_get_product_async.py | 1 - ...ed_product_search_get_product_set_async.py | 1 - ...ted_product_search_get_product_set_sync.py | 1 - ...nerated_product_search_get_product_sync.py | 1 - ...roduct_search_get_reference_image_async.py | 1 - ...product_search_get_reference_image_sync.py | 1 - ...roduct_search_import_product_sets_async.py | 1 - ...product_search_import_product_sets_sync.py | 1 - ..._product_search_list_product_sets_async.py | 1 - ...d_product_search_list_product_sets_sync.py | 1 - ...ated_product_search_list_products_async.py | 1 - ...arch_list_products_in_product_set_async.py | 1 - ...earch_list_products_in_product_set_sync.py | 1 - ...rated_product_search_list_products_sync.py | 1 - ...duct_search_list_reference_images_async.py | 1 - ...oduct_search_list_reference_images_sync.py | 1 - ...ted_product_search_update_product_async.py | 4 +- ...product_search_update_product_set_async.py | 4 +- ..._product_search_update_product_set_sync.py | 4 +- ...ated_product_search_update_product_sync.py | 4 +- ...otator_async_batch_annotate_files_async.py | 4 +- ...notator_async_batch_annotate_files_sync.py | 4 +- ...tator_async_batch_annotate_images_async.py | 4 +- ...otator_async_batch_annotate_images_sync.py | 4 +- ...ge_annotator_batch_annotate_files_async.py | 4 +- ...age_annotator_batch_annotate_files_sync.py | 4 +- ...e_annotator_batch_annotate_images_async.py | 4 +- ...ge_annotator_batch_annotate_images_sync.py | 4 +- ...ted_product_search_create_product_async.py | 1 - ...product_search_create_product_set_async.py | 1 - ..._product_search_create_product_set_sync.py | 1 - ...ated_product_search_create_product_sync.py | 1 - ...uct_search_create_reference_image_async.py | 1 - ...duct_search_create_reference_image_sync.py | 1 - ...erated_product_search_get_product_async.py | 1 - ...ed_product_search_get_product_set_async.py | 1 - ...ted_product_search_get_product_set_sync.py | 1 - ...nerated_product_search_get_product_sync.py | 1 - ...roduct_search_get_reference_image_async.py | 1 - ...product_search_get_reference_image_sync.py | 1 - ...roduct_search_import_product_sets_async.py | 1 - ...product_search_import_product_sets_sync.py | 1 - ..._product_search_list_product_sets_async.py | 1 - ...d_product_search_list_product_sets_sync.py | 1 - ...ated_product_search_list_products_async.py | 1 - ...arch_list_products_in_product_set_async.py | 1 - ...earch_list_products_in_product_set_sync.py | 1 - ...rated_product_search_list_products_sync.py | 1 - ...duct_search_list_reference_images_async.py | 1 - ...oduct_search_list_reference_images_sync.py | 1 - ...ted_product_search_purge_products_async.py | 1 - ...ated_product_search_purge_products_sync.py | 1 - ...ted_product_search_update_product_async.py | 4 +- ...product_search_update_product_set_async.py | 4 +- ..._product_search_update_product_set_sync.py | 4 +- ...ated_product_search_update_product_sync.py | 4 +- packages/google-cloud-vision/setup.py | 11 +- .../google-cloud-vision/tests/__init__.py | 1 + .../tests/unit/__init__.py | 1 + .../tests/unit/gapic/__init__.py | 1 + .../tests/unit/gapic/vision_v1/__init__.py | 1 + .../gapic/vision_v1/test_image_annotator.py | 2569 ++---- .../gapic/vision_v1/test_product_search.py | 8219 +++++++---------- .../unit/gapic/vision_v1p1beta1/__init__.py | 1 + .../vision_v1p1beta1/test_image_annotator.py | 1496 +-- .../unit/gapic/vision_v1p2beta1/__init__.py | 1 + .../vision_v1p2beta1/test_image_annotator.py | 1834 ++-- .../unit/gapic/vision_v1p3beta1/__init__.py | 1 + .../vision_v1p3beta1/test_image_annotator.py | 1856 ++-- .../vision_v1p3beta1/test_product_search.py | 7874 ++++++---------- .../unit/gapic/vision_v1p4beta1/__init__.py | 1 + .../vision_v1p4beta1/test_image_annotator.py | 2530 ++--- .../vision_v1p4beta1/test_product_search.py | 8174 +++++++--------- 244 files changed, 26856 insertions(+), 43254 deletions(-) create mode 100644 .librarian/generate-request.json 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, From 3858e542167bce2f8f7504827ccbc57bead950e2 Mon Sep 17 00:00:00 2001 From: ohmayr Date: Wed, 21 Jan 2026 19:34:43 +0000 Subject: [PATCH 2/5] fix ruff settings --- .generator/cli.py | 37 +- .generator/ruff.toml | 16 + packages/google-cloud-vision/docs/conf.py | 10 +- .../google/cloud/vision/__init__.py | 362 +- .../google/cloud/vision_v1/__init__.py | 430 +- .../services/image_annotator/__init__.py | 6 +- .../services/image_annotator/async_client.py | 279 +- .../services/image_annotator/client.py | 453 +- .../image_annotator/transports/__init__.py | 20 +- .../image_annotator/transports/base.py | 148 +- .../image_annotator/transports/grpc.py | 178 +- .../transports/grpc_asyncio.py | 186 +- .../image_annotator/transports/rest.py | 797 +- .../image_annotator/transports/rest_base.py | 317 +- .../services/product_search/__init__.py | 6 +- .../services/product_search/async_client.py | 895 +- .../services/product_search/client.py | 1030 +- .../services/product_search/pagers.py | 268 +- .../product_search/transports/__init__.py | 20 +- .../product_search/transports/base.py | 370 +- .../product_search/transports/grpc.py | 426 +- .../product_search/transports/grpc_asyncio.py | 461 +- .../product_search/transports/rest.py | 2534 +++-- .../product_search/transports/rest_base.py | 793 +- .../google/cloud/vision_v1/types/__init__.py | 170 +- .../google/cloud/vision_v1/types/geometry.py | 19 +- .../cloud/vision_v1/types/image_annotator.py | 334 +- .../cloud/vision_v1/types/product_search.py | 24 +- .../vision_v1/types/product_search_service.py | 131 +- .../cloud/vision_v1/types/text_annotation.py | 77 +- .../cloud/vision_v1/types/web_detection.py | 25 +- .../google/cloud/vision_v1p1beta1/__init__.py | 219 +- .../services/image_annotator/__init__.py | 6 +- .../services/image_annotator/async_client.py | 157 +- .../services/image_annotator/client.py | 293 +- .../image_annotator/transports/__init__.py | 20 +- .../image_annotator/transports/base.py | 104 +- .../image_annotator/transports/grpc.py | 111 +- .../transports/grpc_asyncio.py | 117 +- .../image_annotator/transports/rest.py | 202 +- .../image_annotator/transports/rest_base.py | 79 +- .../cloud/vision_v1p1beta1/types/__init__.py | 68 +- .../cloud/vision_v1p1beta1/types/geometry.py | 13 +- .../vision_v1p1beta1/types/image_annotator.py | 207 +- .../vision_v1p1beta1/types/text_annotation.py | 77 +- .../vision_v1p1beta1/types/web_detection.py | 25 +- .../google/cloud/vision_v1p2beta1/__init__.py | 266 +- .../services/image_annotator/__init__.py | 6 +- .../services/image_annotator/async_client.py | 198 +- .../services/image_annotator/client.py | 334 +- .../image_annotator/transports/__init__.py | 20 +- .../image_annotator/transports/base.py | 121 +- .../image_annotator/transports/grpc.py | 136 +- .../transports/grpc_asyncio.py | 143 +- .../image_annotator/transports/rest.py | 393 +- .../image_annotator/transports/rest_base.py | 119 +- .../cloud/vision_v1p2beta1/types/__init__.py | 92 +- .../cloud/vision_v1p2beta1/types/geometry.py | 19 +- .../vision_v1p2beta1/types/image_annotator.py | 279 +- .../vision_v1p2beta1/types/text_annotation.py | 77 +- .../vision_v1p2beta1/types/web_detection.py | 25 +- .../google/cloud/vision_v1p3beta1/__init__.py | 402 +- .../services/image_annotator/__init__.py | 6 +- .../services/image_annotator/async_client.py | 198 +- .../services/image_annotator/client.py | 374 +- .../image_annotator/transports/__init__.py | 20 +- .../image_annotator/transports/base.py | 124 +- .../image_annotator/transports/grpc.py | 136 +- .../transports/grpc_asyncio.py | 146 +- .../image_annotator/transports/rest.py | 393 +- .../image_annotator/transports/rest_base.py | 119 +- .../services/product_search/__init__.py | 6 +- .../services/product_search/async_client.py | 845 +- .../services/product_search/client.py | 982 +- .../services/product_search/pagers.py | 268 +- .../product_search/transports/__init__.py | 20 +- .../product_search/transports/base.py | 367 +- .../product_search/transports/grpc.py | 407 +- .../product_search/transports/grpc_asyncio.py | 450 +- .../product_search/transports/rest.py | 2304 +++-- .../product_search/transports/rest_base.py | 715 +- .../cloud/vision_v1p3beta1/types/__init__.py | 156 +- .../cloud/vision_v1p3beta1/types/geometry.py | 19 +- .../vision_v1p3beta1/types/image_annotator.py | 296 +- .../vision_v1p3beta1/types/product_search.py | 24 +- .../types/product_search_service.py | 119 +- .../vision_v1p3beta1/types/text_annotation.py | 77 +- .../vision_v1p3beta1/types/web_detection.py | 25 +- .../google/cloud/vision_v1p4beta1/__init__.py | 440 +- .../services/image_annotator/__init__.py | 6 +- .../services/image_annotator/async_client.py | 268 +- .../services/image_annotator/client.py | 440 +- .../image_annotator/transports/__init__.py | 20 +- .../image_annotator/transports/base.py | 160 +- .../image_annotator/transports/grpc.py | 175 +- .../transports/grpc_asyncio.py | 195 +- .../image_annotator/transports/rest.py | 690 +- .../image_annotator/transports/rest_base.py | 199 +- .../services/product_search/__init__.py | 6 +- .../services/product_search/async_client.py | 884 +- .../services/product_search/client.py | 1017 +- .../services/product_search/pagers.py | 268 +- .../product_search/transports/__init__.py | 20 +- .../product_search/transports/base.py | 379 +- .../product_search/transports/grpc.py | 423 +- .../product_search/transports/grpc_asyncio.py | 467 +- .../product_search/transports/rest.py | 2427 +++-- .../product_search/transports/rest_base.py | 755 +- .../cloud/vision_v1p4beta1/types/__init__.py | 176 +- .../cloud/vision_v1p4beta1/types/face.py | 13 +- .../cloud/vision_v1p4beta1/types/geometry.py | 19 +- .../vision_v1p4beta1/types/image_annotator.py | 350 +- .../vision_v1p4beta1/types/product_search.py | 24 +- .../types/product_search_service.py | 131 +- .../vision_v1p4beta1/types/text_annotation.py | 77 +- .../vision_v1p4beta1/types/web_detection.py | 25 +- packages/google-cloud-vision/noxfile.py | 23 +- ...otator_async_batch_annotate_files_async.py | 4 +- ...notator_async_batch_annotate_files_sync.py | 4 +- ...tator_async_batch_annotate_images_async.py | 4 +- ...otator_async_batch_annotate_images_sync.py | 4 +- ...ge_annotator_batch_annotate_files_async.py | 4 +- ...age_annotator_batch_annotate_files_sync.py | 4 +- ...e_annotator_batch_annotate_images_async.py | 4 +- ...ge_annotator_batch_annotate_images_sync.py | 4 +- ...ted_product_search_create_product_async.py | 1 + ...product_search_create_product_set_async.py | 1 + ..._product_search_create_product_set_sync.py | 1 + ...ated_product_search_create_product_sync.py | 1 + ...uct_search_create_reference_image_async.py | 1 + ...duct_search_create_reference_image_sync.py | 1 + ...erated_product_search_get_product_async.py | 1 + ...ed_product_search_get_product_set_async.py | 1 + ...ted_product_search_get_product_set_sync.py | 1 + ...nerated_product_search_get_product_sync.py | 1 + ...roduct_search_get_reference_image_async.py | 1 + ...product_search_get_reference_image_sync.py | 1 + ...roduct_search_import_product_sets_async.py | 1 + ...product_search_import_product_sets_sync.py | 1 + ..._product_search_list_product_sets_async.py | 1 + ...d_product_search_list_product_sets_sync.py | 1 + ...ated_product_search_list_products_async.py | 1 + ...arch_list_products_in_product_set_async.py | 1 + ...earch_list_products_in_product_set_sync.py | 1 + ...rated_product_search_list_products_sync.py | 1 + ...duct_search_list_reference_images_async.py | 1 + ...oduct_search_list_reference_images_sync.py | 1 + ...ted_product_search_purge_products_async.py | 1 + ...ated_product_search_purge_products_sync.py | 1 + ...ted_product_search_update_product_async.py | 4 +- ...product_search_update_product_set_async.py | 4 +- ..._product_search_update_product_set_sync.py | 4 +- ...ated_product_search_update_product_sync.py | 4 +- ...e_annotator_batch_annotate_images_async.py | 4 +- ...ge_annotator_batch_annotate_images_sync.py | 4 +- ...otator_async_batch_annotate_files_async.py | 4 +- ...notator_async_batch_annotate_files_sync.py | 4 +- ...e_annotator_batch_annotate_images_async.py | 4 +- ...ge_annotator_batch_annotate_images_sync.py | 4 +- ...otator_async_batch_annotate_files_async.py | 4 +- ...notator_async_batch_annotate_files_sync.py | 4 +- ...e_annotator_batch_annotate_images_async.py | 4 +- ...ge_annotator_batch_annotate_images_sync.py | 4 +- ...ted_product_search_create_product_async.py | 1 + ...product_search_create_product_set_async.py | 1 + ..._product_search_create_product_set_sync.py | 1 + ...ated_product_search_create_product_sync.py | 1 + ...uct_search_create_reference_image_async.py | 1 + ...duct_search_create_reference_image_sync.py | 1 + ...erated_product_search_get_product_async.py | 1 + ...ed_product_search_get_product_set_async.py | 1 + ...ted_product_search_get_product_set_sync.py | 1 + ...nerated_product_search_get_product_sync.py | 1 + ...roduct_search_get_reference_image_async.py | 1 + ...product_search_get_reference_image_sync.py | 1 + ...roduct_search_import_product_sets_async.py | 1 + ...product_search_import_product_sets_sync.py | 1 + ..._product_search_list_product_sets_async.py | 1 + ...d_product_search_list_product_sets_sync.py | 1 + ...ated_product_search_list_products_async.py | 1 + ...arch_list_products_in_product_set_async.py | 1 + ...earch_list_products_in_product_set_sync.py | 1 + ...rated_product_search_list_products_sync.py | 1 + ...duct_search_list_reference_images_async.py | 1 + ...oduct_search_list_reference_images_sync.py | 1 + ...ted_product_search_update_product_async.py | 4 +- ...product_search_update_product_set_async.py | 4 +- ..._product_search_update_product_set_sync.py | 4 +- ...ated_product_search_update_product_sync.py | 4 +- ...otator_async_batch_annotate_files_async.py | 4 +- ...notator_async_batch_annotate_files_sync.py | 4 +- ...tator_async_batch_annotate_images_async.py | 4 +- ...otator_async_batch_annotate_images_sync.py | 4 +- ...ge_annotator_batch_annotate_files_async.py | 4 +- ...age_annotator_batch_annotate_files_sync.py | 4 +- ...e_annotator_batch_annotate_images_async.py | 4 +- ...ge_annotator_batch_annotate_images_sync.py | 4 +- ...ted_product_search_create_product_async.py | 1 + ...product_search_create_product_set_async.py | 1 + ..._product_search_create_product_set_sync.py | 1 + ...ated_product_search_create_product_sync.py | 1 + ...uct_search_create_reference_image_async.py | 1 + ...duct_search_create_reference_image_sync.py | 1 + ...erated_product_search_get_product_async.py | 1 + ...ed_product_search_get_product_set_async.py | 1 + ...ted_product_search_get_product_set_sync.py | 1 + ...nerated_product_search_get_product_sync.py | 1 + ...roduct_search_get_reference_image_async.py | 1 + ...product_search_get_reference_image_sync.py | 1 + ...roduct_search_import_product_sets_async.py | 1 + ...product_search_import_product_sets_sync.py | 1 + ..._product_search_list_product_sets_async.py | 1 + ...d_product_search_list_product_sets_sync.py | 1 + ...ated_product_search_list_products_async.py | 1 + ...arch_list_products_in_product_set_async.py | 1 + ...earch_list_products_in_product_set_sync.py | 1 + ...rated_product_search_list_products_sync.py | 1 + ...duct_search_list_reference_images_async.py | 1 + ...oduct_search_list_reference_images_sync.py | 1 + ...ted_product_search_purge_products_async.py | 1 + ...ated_product_search_purge_products_sync.py | 1 + ...ted_product_search_update_product_async.py | 4 +- ...product_search_update_product_set_async.py | 4 +- ..._product_search_update_product_set_sync.py | 4 +- ...ated_product_search_update_product_sync.py | 4 +- packages/google-cloud-vision/setup.py | 11 +- .../google-cloud-vision/tests/__init__.py | 1 - .../tests/unit/__init__.py | 1 - .../tests/unit/gapic/__init__.py | 1 - .../tests/unit/gapic/vision_v1/__init__.py | 1 - .../gapic/vision_v1/test_image_annotator.py | 2606 ++++-- .../gapic/vision_v1/test_product_search.py | 8306 ++++++++++------- .../unit/gapic/vision_v1p1beta1/__init__.py | 1 - .../vision_v1p1beta1/test_image_annotator.py | 1526 ++- .../unit/gapic/vision_v1p2beta1/__init__.py | 1 - .../vision_v1p2beta1/test_image_annotator.py | 1863 ++-- .../unit/gapic/vision_v1p3beta1/__init__.py | 1 - .../vision_v1p3beta1/test_image_annotator.py | 1887 ++-- .../vision_v1p3beta1/test_product_search.py | 7954 ++++++++++------ .../unit/gapic/vision_v1p4beta1/__init__.py | 1 - .../vision_v1p4beta1/test_image_annotator.py | 2562 +++-- .../vision_v1p4beta1/test_product_search.py | 8252 +++++++++------- 242 files changed, 42915 insertions(+), 26105 deletions(-) create mode 100644 .generator/ruff.toml diff --git a/.generator/cli.py b/.generator/cli.py index 2f2b62cd4882..70a8ba63d9de 100644 --- a/.generator/cli.py +++ b/.generator/cli.py @@ -392,36 +392,35 @@ def _run_post_processor(output: str, library_id: str, is_mono_repo: bool): # 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)...") + ruff_config_path = Path("/usr/local/google/home/omairn/git/googleapis/google-cloud-python/.generator/ruff.toml").resolve() + + if not ruff_config_path.exists(): + logger.warning(f"⚠️ Could not find Ruff config at {ruff_config_path}. Using defaults.") + try: + + subprocess.run(["ruff", "--version"], check=False) + logger.info("Running Ruff Check (Imports)...") + base_args = ["ruff", "--config", str(ruff_config_path)] + # 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 + base_args + ["check", "--fix", "."], + check=True, ) # 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 + base_args + ["format", "."], + check=True, ) + logger.info("Ruff formatting completed successfully.") + except FileNotFoundError: logger.warning("⚠️ Ruff binary not found. Code will be unformatted.") logger.warning(" Please run: pip install ruff") + except subprocess.CalledProcessError as e: + logger.error(f"❌ Ruff failed with exit code {e.returncode}.") logger.info("Python post-processor ran successfully.") diff --git a/.generator/ruff.toml b/.generator/ruff.toml new file mode 100644 index 000000000000..2aa15ba74c1b --- /dev/null +++ b/.generator/ruff.toml @@ -0,0 +1,16 @@ +# .generator/ruff.toml + +# Match Black's line length +line-length = 88 + +[lint] +# Enable Import sorting (isort) +select = ["I"] + +[lint.isort] +# Force 'google' to be recognized as a first-party import +known-first-party = ["google"] + +[format] +# Strictly enforce double quotes (Black style) +quote-style = "double" \ 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 0b8a5fcc323a..e8dcac6902ba 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 = u"google-cloud-vision" -copyright = u"2025, Google, LLC" -author = u"Google APIs" +project = "google-cloud-vision" +copyright = "2025, Google, LLC" +author = "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", - u"google-cloud-vision Documentation", + "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 407f2fc74ef2..27def75b91c6 100644 --- a/packages/google-cloud-vision/google/cloud/vision/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision/__init__.py @@ -19,181 +19,195 @@ from google.cloud.vision_v1 import ImageAnnotatorClient -from google.cloud.vision_v1.services.image_annotator.async_client import ImageAnnotatorAsyncClient +from google.cloud.vision_v1.services.image_annotator.async_client import ( + ImageAnnotatorAsyncClient, +) +from google.cloud.vision_v1.services.product_search.async_client import ( + ProductSearchAsyncClient, +) from google.cloud.vision_v1.services.product_search.client import ProductSearchClient -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.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.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 4a138f8763ff..3084970c5286 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from google.cloud.vision_v1 import gapic_version as package_version +import sys import google.api_core as api_core -import sys +from google.cloud.vision_v1 import gapic_version as package_version __version__ = package_version.__version__ @@ -28,123 +28,121 @@ import importlib_metadata as metadata -from .services.image_annotator import ImageAnnotatorClient -from .services.image_annotator import ImageAnnotatorAsyncClient -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 .services.image_annotator import ImageAnnotatorAsyncClient, ImageAnnotatorClient +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 .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 warnings import sys + import warnings _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. @@ -182,113 +180,117 @@ 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/") + 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 b1663fdd632d..c7f40549e472 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 .client import ImageAnnotatorClient from .async_client import ImageAnnotatorAsyncClient +from .client import ImageAnnotatorClient __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 6839ffee6c08..82888d085020 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 @@ -14,42 +14,56 @@ # limitations under the License. # import logging as std_logging -from collections import OrderedDict import re -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 collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) -from google.api_core.client_options import ClientOptions +import google.protobuf 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.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.vision_v1 import gapic_version as package_version +from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore +from google.api_core import ( + operation, # type: ignore + operation_async, # type: ignore +) from google.cloud.vision_v1.types import image_annotator -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport +from google.longrunning import operations_pb2 # type: ignore + from .client import ImageAnnotatorClient +from .transports.base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport 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 @@ -70,16 +84,30 @@ 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): @@ -94,7 +122,9 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ImageAnnotatorAsyncClient: The constructed client. """ - return ImageAnnotatorClient.from_service_account_info.__func__(ImageAnnotatorAsyncClient, info, *args, **kwargs) # type: ignore + return ImageAnnotatorClient.from_service_account_info.__func__( + ImageAnnotatorAsyncClient, info, *args, **kwargs + ) # type: ignore @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -110,12 +140,16 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ImageAnnotatorAsyncClient: The constructed client. """ - return ImageAnnotatorClient.from_service_account_file.__func__(ImageAnnotatorAsyncClient, filename, *args, **kwargs) # type: ignore + return ImageAnnotatorClient.from_service_account_file.__func__( + ImageAnnotatorAsyncClient, filename, *args, **kwargs + ) # type: ignore 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: @@ -178,12 +212,16 @@ 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: @@ -238,31 +276,43 @@ def __init__(self, *, 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. @@ -320,10 +370,14 @@ 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. @@ -337,7 +391,9 @@ 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() @@ -353,14 +409,17 @@ 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. @@ -425,10 +484,14 @@ 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. @@ -442,7 +505,9 @@ 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() @@ -458,15 +523,20 @@ 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. @@ -548,10 +618,14 @@ 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. @@ -567,7 +641,9 @@ 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() @@ -591,14 +667,19 @@ 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 @@ -669,10 +750,14 @@ 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. @@ -686,7 +771,9 @@ 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() @@ -748,8 +835,7 @@ 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. @@ -757,7 +843,11 @@ 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 @@ -768,12 +858,13 @@ 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__) -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +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__ = ( - "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 9cfbf978db64..5c41121995a5 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 @@ -13,27 +13,38 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict -from http import HTTPStatus import json import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) -from google.cloud.vision_v1 import gapic_version as package_version - +import google.protobuf 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.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.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.cloud.vision_v1 import gapic_version as package_version +from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -42,17 +53,21 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore +from google.api_core import ( + operation, # type: ignore + operation_async, # type: ignore +) from google.cloud.vision_v1.types import image_annotator -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO +from google.longrunning import operations_pb2 # type: ignore + +from .transports.base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport from .transports.grpc import ImageAnnotatorGrpcTransport from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport from .transports.rest import ImageAnnotatorRestTransport @@ -65,14 +80,16 @@ class ImageAnnotatorClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _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: @@ -148,14 +165,16 @@ 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" @@ -194,8 +213,7 @@ 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) @@ -212,84 +230,132 @@ 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: @@ -321,14 +387,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio 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 @@ -341,7 +411,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # 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 @@ -366,7 +438,9 @@ 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 @@ -389,7 +463,9 @@ 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: @@ -405,17 +481,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ 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: @@ -451,15 +535,18 @@ 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 @@ -492,12 +579,16 @@ 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: @@ -552,14 +643,22 @@ def __init__(self, *, 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 @@ -570,7 +669,9 @@ def __init__(self, *, 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 @@ -579,30 +680,40 @@ def __init__(self, *, 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 " - "directly." + "When providing a transport instance, provide its scopes directly." ) 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) @@ -621,28 +732,41 @@ def __init__(self, *, ) 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. @@ -700,10 +824,14 @@ 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. @@ -732,14 +860,17 @@ 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. @@ -804,10 +935,14 @@ 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. @@ -836,15 +971,20 @@ 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. @@ -926,10 +1066,14 @@ 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. @@ -944,7 +1088,9 @@ 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() @@ -968,14 +1114,19 @@ 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 @@ -1046,10 +1197,14 @@ 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. @@ -1062,7 +1217,9 @@ 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() @@ -1137,8 +1294,7 @@ 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. @@ -1147,7 +1303,11 @@ 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 @@ -1156,18 +1316,11 @@ 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 d3a583db5759..1de28b3fb87a 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,20 +19,18 @@ from .base import ImageAnnotatorTransport from .grpc import ImageAnnotatorGrpcTransport from .grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport -from .rest import ImageAnnotatorRestTransport -from .rest import ImageAnnotatorRestInterceptor - +from .rest import ImageAnnotatorRestInterceptor, ImageAnnotatorRestTransport # 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 dbe3c7a8d54b..b3ca63f6ea82 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,21 @@ 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 +import google.auth # type: ignore +import google.protobuf from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, operations_v1 from google.api_core import retry as retries -from google.api_core import operations_v1 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 from google.cloud.vision_v1.types import image_annotator -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # 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,24 +40,25 @@ 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: @@ -93,31 +93,43 @@ 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=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + 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=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + 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 @@ -192,14 +204,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() @@ -209,39 +221,45 @@ 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 @@ -258,6 +276,4 @@ 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 60515ff900de..9652736cae87 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 @@ -19,24 +19,23 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union -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.protobuf.json_format import MessageToJson -import google.protobuf.message - import grpc # type: ignore import proto # type: ignore +import google.auth # type: ignore +import google.protobuf.message +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore from google.cloud.vision_v1.types import image_annotator -from google.longrunning import operations_pb2 # type: ignore -from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport 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,7 +45,9 @@ 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 +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.ImageAnnotator", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -78,7 +79,11 @@ 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) @@ -93,7 +98,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, @@ -118,23 +123,26 @@ 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: @@ -258,19 +266,23 @@ def __init__(self, *, ) 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. @@ -306,13 +318,12 @@ def create_channel(cls, 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 @@ -332,9 +343,12 @@ 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 @@ -350,18 +364,21 @@ def batch_annotate_images(self) -> Callable[ # 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 @@ -384,18 +401,20 @@ def batch_annotate_files(self) -> Callable[ # 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 @@ -421,18 +440,22 @@ def async_batch_annotate_images(self) -> Callable[ # 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', - request_serializer=image_annotator.AsyncBatchAnnotateImagesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, + 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 @@ -453,13 +476,15 @@ def async_batch_annotate_files(self) -> Callable[ # 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', - request_serializer=image_annotator.AsyncBatchAnnotateFilesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, + 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() @@ -468,8 +493,7 @@ 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 @@ -487,6 +511,4 @@ 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 945f107b65f7..e2af0b6189ee 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,32 +15,31 @@ # import inspect import json -import pickle import logging as std_logging +import pickle 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 +import grpc # type: ignore +import proto # type: ignore +from grpc.experimental import aio # type: ignore + +import google.protobuf.message 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.api_core import operations_v1 -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.cloud.vision_v1.types import image_annotator +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 grpc.experimental import aio # type: ignore -from google.cloud.vision_v1.types import image_annotator -from google.longrunning import operations_pb2 # type: ignore -from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO +from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport 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 @@ -48,9 +47,13 @@ _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): @@ -71,7 +74,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, @@ -82,7 +85,11 @@ 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) @@ -97,7 +104,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, @@ -127,13 +134,15 @@ 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. @@ -164,24 +173,26 @@ def create_channel(cls, 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: @@ -307,7 +318,9 @@ def __init__(self, *, 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) @@ -338,9 +351,12 @@ 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 @@ -356,18 +372,21 @@ def batch_annotate_images(self) -> Callable[ # 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 @@ -390,18 +409,21 @@ def batch_annotate_files(self) -> Callable[ # 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 @@ -427,18 +449,23 @@ def async_batch_annotate_images(self) -> Callable[ # 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', - request_serializer=image_annotator.AsyncBatchAnnotateImagesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, + 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 @@ -459,16 +486,18 @@ def async_batch_annotate_files(self) -> Callable[ # 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', - request_serializer=image_annotator.AsyncBatchAnnotateFilesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, + 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, @@ -553,8 +582,7 @@ 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 @@ -568,6 +596,4 @@ 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 a4c5ebba1ceb..2b495669c9f8 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,33 +13,26 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import logging -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 retry as retries -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 json # type: ignore +import logging import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +from requests import __version__ as requests_version +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_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.cloud.vision_v1.types import image_annotator from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format - -from .rest_base import _BaseImageAnnotatorRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseImageAnnotatorRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -48,6 +41,7 @@ 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 @@ -116,7 +110,15 @@ 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 @@ -124,7 +126,9 @@ def pre_async_batch_annotate_files(self, request: image_annotator.AsyncBatchAnno """ 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` @@ -137,7 +141,11 @@ def post_async_batch_annotate_files(self, response: operations_pb2.Operation) -> """ 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 @@ -152,7 +160,14 @@ def post_async_batch_annotate_files_with_metadata(self, response: operations_pb2 """ 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 @@ -160,7 +175,9 @@ def pre_async_batch_annotate_images(self, request: image_annotator.AsyncBatchAnn """ 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` @@ -173,7 +190,11 @@ def post_async_batch_annotate_images(self, response: operations_pb2.Operation) - """ 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 @@ -188,7 +209,14 @@ def post_async_batch_annotate_images_with_metadata(self, response: operations_pb """ 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 @@ -196,7 +224,9 @@ def pre_batch_annotate_files(self, request: image_annotator.BatchAnnotateFilesRe """ 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` @@ -209,7 +239,14 @@ def post_batch_annotate_files(self, response: image_annotator.BatchAnnotateFiles """ 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 @@ -224,7 +261,14 @@ def post_batch_annotate_files_with_metadata(self, response: image_annotator.Batc """ 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 @@ -232,7 +276,9 @@ def pre_batch_annotate_images(self, request: image_annotator.BatchAnnotateImages """ 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` @@ -245,7 +291,14 @@ def post_batch_annotate_images(self, response: image_annotator.BatchAnnotateImag """ 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 @@ -261,8 +314,12 @@ def post_batch_annotate_images_with_metadata(self, response: image_annotator.Bat 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 @@ -304,20 +361,21 @@ 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: @@ -361,10 +419,11 @@ def __init__(self, *, 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) @@ -381,40 +440,46 @@ 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") @@ -426,77 +491,91 @@ 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() - 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, @@ -505,7 +584,17 @@ def __call__(self, ) # 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. @@ -518,20 +607,24 @@ def __call__(self, 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"], @@ -540,7 +633,10 @@ def __call__(self, ) return resp - class _AsyncBatchAnnotateImages(_BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateImages, ImageAnnotatorRestStub): + class _AsyncBatchAnnotateImages( + _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateImages, + ImageAnnotatorRestStub, + ): def __hash__(self): return hash("ImageAnnotatorRestTransport.AsyncBatchAnnotateImages") @@ -552,76 +648,90 @@ 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() - 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, @@ -630,7 +740,17 @@ def __call__(self, ) # 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. @@ -643,20 +763,24 @@ def __call__(self, 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"], @@ -665,7 +789,9 @@ def __call__(self, ) return resp - class _BatchAnnotateFiles(_BaseImageAnnotatorRestTransport._BaseBatchAnnotateFiles, ImageAnnotatorRestStub): + class _BatchAnnotateFiles( + _BaseImageAnnotatorRestTransport._BaseBatchAnnotateFiles, ImageAnnotatorRestStub + ): def __hash__(self): return hash("ImageAnnotatorRestTransport.BatchAnnotateFiles") @@ -677,27 +803,29 @@ 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: @@ -719,30 +847,42 @@ def __call__(self, 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, @@ -751,7 +891,15 @@ def __call__(self, ) # 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. @@ -766,20 +914,26 @@ def __call__(self, 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"], @@ -788,7 +942,10 @@ def __call__(self, ) return resp - class _BatchAnnotateImages(_BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages, ImageAnnotatorRestStub): + class _BatchAnnotateImages( + _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages, + ImageAnnotatorRestStub, + ): def __hash__(self): return hash("ImageAnnotatorRestTransport.BatchAnnotateImages") @@ -800,27 +957,29 @@ 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: @@ -844,30 +1003,42 @@ def __call__(self, 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, @@ -876,7 +1047,15 @@ def __call__(self, ) # 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. @@ -891,20 +1070,26 @@ def __call__(self, 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"], @@ -914,42 +1099,58 @@ def __call__(self, 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") @@ -961,27 +1162,28 @@ 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: @@ -999,30 +1201,40 @@ def __call__(self, 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, @@ -1031,7 +1243,14 @@ def __call__(self, ) # 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. @@ -1042,19 +1261,21 @@ def __call__(self, 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, @@ -1071,6 +1292,4 @@ 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 c1211696662f..41b6dd3542ea 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,18 +14,15 @@ # 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.cloud.vision_v1.types import image_annotator from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport class _BaseImageAnnotatorRestTransport(ImageAnnotatorTransport): @@ -41,14 +38,16 @@ 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,7 +71,9 @@ def __init__(self, *, # 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() @@ -83,37 +84,41 @@ def __init__(self, *, 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 @@ -128,17 +133,23 @@ 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 @@ -147,30 +158,34 @@ 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 @@ -185,17 +200,23 @@ 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 @@ -204,30 +225,34 @@ 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 @@ -242,17 +267,23 @@ 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 @@ -261,30 +292,34 @@ 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 @@ -299,17 +334,23 @@ 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 @@ -320,38 +361,36 @@ 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 ff3cc167408d..f2e4fe58e8df 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 .client import ProductSearchClient from .async_client import ProductSearchAsyncClient +from .client import ProductSearchClient __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 8396ac1b3798..372b535dd43d 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 @@ -14,48 +14,63 @@ # limitations under the License. # import logging as std_logging -from collections import OrderedDict import re -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 collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) -from google.api_core.client_options import ClientOptions +import google.protobuf 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.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.vision_v1 import gapic_version as package_version +from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore +from google.api_core import ( + operation, # type: ignore + operation_async, # 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.cloud.vision_v1.types import geometry, product_search_service +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import ( + empty_pb2, # type: ignore + field_mask_pb2, # type: ignore + timestamp_pb2, # type: ignore +) from google.rpc import status_pb2 # type: ignore -from .transports.base import ProductSearchTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ProductSearchGrpcAsyncIOTransport + from .client import ProductSearchClient +from .transports.base import DEFAULT_CLIENT_INFO, ProductSearchTransport +from .transports.grpc_asyncio import ProductSearchGrpcAsyncIOTransport 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: @@ -91,17 +106,33 @@ 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): @@ -116,7 +147,9 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ProductSearchAsyncClient: The constructed client. """ - return ProductSearchClient.from_service_account_info.__func__(ProductSearchAsyncClient, info, *args, **kwargs) # type: ignore + return ProductSearchClient.from_service_account_info.__func__( + ProductSearchAsyncClient, info, *args, **kwargs + ) # type: ignore @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -132,12 +165,16 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ProductSearchAsyncClient: The constructed client. """ - return ProductSearchClient.from_service_account_file.__func__(ProductSearchAsyncClient, filename, *args, **kwargs) # type: ignore + return ProductSearchClient.from_service_account_file.__func__( + ProductSearchAsyncClient, filename, *args, **kwargs + ) # type: ignore 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,12 +237,16 @@ 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: @@ -260,33 +301,43 @@ def __init__(self, *, 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: @@ -368,10 +419,14 @@ 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. @@ -389,14 +444,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. @@ -413,14 +468,17 @@ 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: @@ -487,10 +545,14 @@ 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. @@ -504,14 +566,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. @@ -539,14 +601,17 @@ 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: @@ -612,10 +677,14 @@ 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. @@ -629,14 +698,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. @@ -653,15 +722,18 @@ 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. @@ -737,10 +809,14 @@ 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. @@ -756,14 +832,16 @@ 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. @@ -780,14 +858,17 @@ 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. @@ -841,10 +922,14 @@ 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. @@ -858,14 +943,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. @@ -879,16 +964,19 @@ 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: @@ -969,10 +1057,14 @@ 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. @@ -990,14 +1082,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. @@ -1014,14 +1106,17 @@ 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: @@ -1088,10 +1183,14 @@ 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. @@ -1105,14 +1204,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. @@ -1140,14 +1239,15 @@ 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: @@ -1208,10 +1308,14 @@ 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. @@ -1225,14 +1329,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. @@ -1249,15 +1353,18 @@ 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. @@ -1337,10 +1444,14 @@ 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. @@ -1356,14 +1467,16 @@ 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. @@ -1380,14 +1493,17 @@ 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 @@ -1442,10 +1558,14 @@ 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. @@ -1459,14 +1579,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. @@ -1480,16 +1600,19 @@ 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 @@ -1592,10 +1715,14 @@ 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. @@ -1613,14 +1740,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. @@ -1637,14 +1764,17 @@ 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 @@ -1702,10 +1832,14 @@ 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. @@ -1719,14 +1853,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. @@ -1740,14 +1874,17 @@ 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: @@ -1816,10 +1953,14 @@ 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. @@ -1833,14 +1974,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. @@ -1868,14 +2009,17 @@ 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: @@ -1939,10 +2083,14 @@ 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. @@ -1956,14 +2104,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. @@ -1980,15 +2128,18 @@ 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. @@ -2059,14 +2210,20 @@ 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 @@ -2078,14 +2235,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. @@ -2099,15 +2256,18 @@ 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 @@ -2170,14 +2330,20 @@ 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 @@ -2189,14 +2355,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. @@ -2210,14 +2376,17 @@ 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. @@ -2289,14 +2458,20 @@ 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 @@ -2306,14 +2481,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. @@ -2341,15 +2516,20 @@ 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. @@ -2439,10 +2619,14 @@ 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. @@ -2458,14 +2642,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. @@ -2490,14 +2674,17 @@ 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. @@ -2596,10 +2783,14 @@ 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. @@ -2613,14 +2804,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. @@ -2683,8 +2874,7 @@ 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. @@ -2692,7 +2882,11 @@ 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 @@ -2703,12 +2897,13 @@ 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__) -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +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__ = ( - "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 5eb03cee32e0..5f56f98e08a6 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 @@ -13,27 +13,38 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict -from http import HTTPStatus import json import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) -from google.cloud.vision_v1 import gapic_version as package_version - +import google.protobuf 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.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.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.cloud.vision_v1 import gapic_version as package_version +from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -42,23 +53,28 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore +from google.api_core import ( + operation, # type: ignore + operation_async, # 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.cloud.vision_v1.types import geometry, product_search_service +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import ( + empty_pb2, # type: ignore + field_mask_pb2, # type: ignore + timestamp_pb2, # type: ignore +) from google.rpc import status_pb2 # type: ignore -from .transports.base import ProductSearchTransport, DEFAULT_CLIENT_INFO + +from .transports.base import DEFAULT_CLIENT_INFO, ProductSearchTransport from .transports.grpc import ProductSearchGrpcTransport from .transports.grpc_asyncio import ProductSearchGrpcAsyncIOTransport from .transports.rest import ProductSearchRestTransport @@ -71,14 +87,16 @@ 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: @@ -168,14 +186,16 @@ 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,8 +234,7 @@ 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) @@ -232,95 +251,156 @@ 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: @@ -352,14 +432,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio 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 @@ -372,7 +456,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # 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 @@ -397,7 +483,9 @@ 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 @@ -420,7 +508,9 @@ 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: @@ -436,17 +526,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ 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: @@ -482,15 +580,18 @@ 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 @@ -523,12 +624,16 @@ 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: @@ -583,14 +688,22 @@ def __init__(self, *, 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 @@ -601,7 +714,9 @@ def __init__(self, *, 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 @@ -610,30 +725,40 @@ def __init__(self, *, 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 " - "directly." + "When providing a transport instance, provide its scopes directly." ) 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) @@ -652,30 +777,41 @@ def __init__(self, *, ) 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: @@ -757,10 +893,14 @@ 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. @@ -782,9 +922,7 @@ 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. @@ -801,14 +939,17 @@ 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: @@ -875,10 +1016,14 @@ 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. @@ -896,9 +1041,7 @@ 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. @@ -926,14 +1069,17 @@ 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: @@ -999,10 +1145,14 @@ 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. @@ -1020,9 +1170,7 @@ 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. @@ -1039,15 +1187,18 @@ 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. @@ -1123,10 +1274,14 @@ 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. @@ -1146,9 +1301,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. @@ -1165,14 +1320,17 @@ 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. @@ -1226,10 +1384,14 @@ 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. @@ -1247,9 +1409,7 @@ 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. @@ -1263,16 +1423,19 @@ 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: @@ -1353,10 +1516,14 @@ 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. @@ -1378,9 +1545,7 @@ 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. @@ -1397,14 +1562,17 @@ 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: @@ -1471,10 +1639,14 @@ 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. @@ -1492,9 +1664,7 @@ 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. @@ -1522,14 +1692,15 @@ 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: @@ -1590,10 +1761,14 @@ 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. @@ -1611,9 +1786,7 @@ 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. @@ -1630,15 +1803,18 @@ 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. @@ -1718,10 +1894,14 @@ 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. @@ -1741,9 +1921,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. @@ -1760,14 +1940,17 @@ 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 @@ -1822,10 +2005,14 @@ 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. @@ -1843,9 +2030,7 @@ 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. @@ -1859,16 +2044,19 @@ 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 @@ -1971,10 +2159,14 @@ 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. @@ -1996,9 +2188,7 @@ 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. @@ -2015,14 +2205,17 @@ 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 @@ -2080,10 +2273,14 @@ 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. @@ -2101,9 +2298,7 @@ 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. @@ -2117,14 +2312,17 @@ 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: @@ -2193,10 +2391,14 @@ 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. @@ -2214,9 +2416,7 @@ 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. @@ -2244,14 +2444,17 @@ 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: @@ -2315,10 +2518,14 @@ 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. @@ -2336,9 +2543,7 @@ 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. @@ -2355,15 +2560,18 @@ 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. @@ -2434,14 +2642,20 @@ 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. @@ -2452,14 +2666,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. @@ -2473,15 +2687,18 @@ 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 @@ -2544,14 +2761,20 @@ 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. @@ -2562,14 +2785,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. @@ -2583,14 +2806,17 @@ 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. @@ -2662,14 +2888,20 @@ 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. @@ -2678,14 +2910,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. @@ -2713,15 +2945,20 @@ 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. @@ -2811,10 +3048,14 @@ 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. @@ -2834,9 +3075,7 @@ 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. @@ -2861,14 +3100,17 @@ 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. @@ -2967,10 +3209,14 @@ 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. @@ -2988,9 +3234,7 @@ 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. @@ -3066,8 +3310,7 @@ 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. @@ -3076,7 +3319,11 @@ 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 @@ -3085,18 +3332,11 @@ 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 4cd45f704986..77727b5abef2 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,13 +13,27 @@ # 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 @@ -44,14 +58,17 @@ 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: @@ -84,7 +101,12 @@ 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]: @@ -92,7 +114,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: @@ -112,14 +134,19 @@ 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: @@ -148,12 +175,20 @@ 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: @@ -163,7 +198,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: @@ -183,14 +218,17 @@ 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: @@ -223,7 +261,12 @@ 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]: @@ -231,7 +274,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: @@ -251,14 +294,17 @@ 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: @@ -291,8 +337,14 @@ 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: @@ -302,7 +354,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: @@ -322,14 +374,17 @@ 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: @@ -362,7 +417,12 @@ 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]: @@ -370,7 +430,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: @@ -390,14 +450,19 @@ 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: @@ -426,12 +491,20 @@ 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: @@ -441,7 +514,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: @@ -461,14 +534,17 @@ 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: @@ -497,11 +573,18 @@ 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]: @@ -509,7 +592,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: @@ -529,14 +612,19 @@ 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: @@ -565,12 +653,20 @@ 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: @@ -580,4 +676,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 f5f6aac78c26..e3bd7adc48d8 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,20 +19,18 @@ from .base import ProductSearchTransport from .grpc import ProductSearchGrpcTransport from .grpc_asyncio import ProductSearchGrpcAsyncIOTransport -from .rest import ProductSearchRestTransport -from .rest import ProductSearchRestInterceptor - +from .rest import ProductSearchRestInterceptor, ProductSearchRestTransport # 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 ea7b1e807892..cd1f1d070427 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,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 +import google.auth # type: ignore +import google.protobuf from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, operations_v1 from google.api_core import retry as retries -from google.api_core import operations_v1 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 from google.cloud.vision_v1.types import product_search_service -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # 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,24 +41,25 @@ 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: @@ -94,31 +94,43 @@ 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=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + 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=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + 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 @@ -134,8 +146,7 @@ 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, @@ -207,8 +218,7 @@ 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, @@ -280,8 +290,7 @@ 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, @@ -383,8 +392,7 @@ 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, @@ -396,8 +404,7 @@ 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, @@ -408,14 +415,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() @@ -425,174 +432,207 @@ 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 @@ -609,6 +649,4 @@ 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 f46d22405c32..51a48068ff4a 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 @@ -19,25 +19,24 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union -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.protobuf.json_format import MessageToJson -import google.protobuf.message - import grpc # type: ignore import proto # type: ignore +import google.auth # type: ignore +import google.protobuf.message +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore from google.cloud.vision_v1.types import product_search_service -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore -from .base import ProductSearchTransport, DEFAULT_CLIENT_INFO +from google.protobuf.json_format import MessageToJson + +from .base import DEFAULT_CLIENT_INFO, ProductSearchTransport 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,7 +46,9 @@ 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 +69,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, @@ -79,7 +80,11 @@ 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) @@ -94,7 +99,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, @@ -133,23 +138,26 @@ 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: @@ -273,19 +281,23 @@ def __init__(self, *, ) 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. @@ -321,13 +333,12 @@ def create_channel(cls, 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 @@ -347,9 +358,12 @@ 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. @@ -369,18 +383,21 @@ def create_product_set(self) -> Callable[ # 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. @@ -400,18 +417,20 @@ def list_product_sets(self) -> Callable[ # 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. @@ -430,18 +449,21 @@ def get_product_set(self) -> Callable[ # 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 @@ -464,18 +486,18 @@ def update_product_set(self) -> Callable[ # 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 @@ -494,18 +516,20 @@ def delete_product_set(self) -> Callable[ # 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. @@ -529,18 +553,21 @@ def create_product(self) -> Callable[ # 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. @@ -560,18 +587,20 @@ def list_products(self) -> Callable[ # 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. @@ -590,18 +619,20 @@ def get_product(self) -> Callable[ # 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``, @@ -631,18 +662,18 @@ def update_product(self) -> Callable[ # 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 @@ -662,18 +693,21 @@ def delete_product(self) -> Callable[ # 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. @@ -709,18 +743,20 @@ def create_reference_image(self) -> Callable[ # 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. @@ -742,18 +778,21 @@ def delete_reference_image(self) -> Callable[ # 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. @@ -774,18 +813,21 @@ def list_reference_images(self) -> Callable[ # 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. @@ -804,18 +846,20 @@ def get_reference_image(self) -> Callable[ # 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 @@ -838,18 +882,22 @@ def add_product_to_product_set(self) -> Callable[ # 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', - request_serializer=product_search_service.AddProductToProductSetRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, + 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. @@ -865,18 +913,23 @@ def remove_product_from_product_set(self) -> Callable[ # 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', - request_serializer=product_search_service.RemoveProductFromProductSetRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, + 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 @@ -898,18 +951,22 @@ def list_products_in_product_set(self) -> Callable[ # 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', - request_serializer=product_search_service.ListProductsInProductSetRequest.serialize, - response_deserializer=product_search_service.ListProductsInProductSetResponse.deserialize, + 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 @@ -935,18 +992,20 @@ def import_product_sets(self) -> Callable[ # 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 @@ -987,13 +1046,13 @@ def purge_products(self) -> Callable[ # 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() @@ -1002,8 +1061,7 @@ 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 @@ -1021,6 +1079,4 @@ 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 e02e6c3b3ddb..b9c12d0229f9 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,33 +15,32 @@ # import inspect import json -import pickle import logging as std_logging +import pickle 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 +import grpc # type: ignore +import proto # type: ignore +from grpc.experimental import aio # type: ignore + +import google.protobuf.message 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.api_core import operations_v1 -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 proto # type: ignore -from grpc.experimental import aio # type: ignore - from google.cloud.vision_v1.types import product_search_service -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore -from .base import ProductSearchTransport, DEFAULT_CLIENT_INFO +from google.protobuf.json_format import MessageToJson + +from .base import DEFAULT_CLIENT_INFO, ProductSearchTransport 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 @@ -49,9 +48,13 @@ _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): @@ -72,7 +75,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, @@ -83,7 +86,11 @@ 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) @@ -98,7 +105,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, @@ -142,13 +149,15 @@ 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. @@ -179,24 +188,26 @@ def create_channel(cls, 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: @@ -322,7 +333,9 @@ def __init__(self, *, 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) @@ -353,9 +366,12 @@ 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. @@ -375,18 +391,21 @@ def create_product_set(self) -> Callable[ # 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. @@ -406,18 +425,21 @@ def list_product_sets(self) -> Callable[ # 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. @@ -436,18 +458,21 @@ def get_product_set(self) -> Callable[ # 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 @@ -470,18 +495,20 @@ def update_product_set(self) -> Callable[ # 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 @@ -500,18 +527,21 @@ def delete_product_set(self) -> Callable[ # 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. @@ -535,18 +565,21 @@ def create_product(self) -> Callable[ # 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. @@ -566,18 +599,21 @@ def list_products(self) -> Callable[ # 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. @@ -596,18 +632,21 @@ def get_product(self) -> Callable[ # 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``, @@ -637,18 +676,20 @@ def update_product(self) -> Callable[ # 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 @@ -668,18 +709,21 @@ def delete_product(self) -> Callable[ # 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. @@ -715,18 +759,20 @@ def create_reference_image(self) -> Callable[ # 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. @@ -748,18 +794,21 @@ def delete_reference_image(self) -> Callable[ # 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. @@ -780,18 +829,21 @@ def list_reference_images(self) -> Callable[ # 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. @@ -810,18 +862,21 @@ def get_reference_image(self) -> Callable[ # 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 @@ -844,18 +899,23 @@ def add_product_to_product_set(self) -> Callable[ # 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', - request_serializer=product_search_service.AddProductToProductSetRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, + 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. @@ -871,18 +931,23 @@ def remove_product_from_product_set(self) -> Callable[ # 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', - request_serializer=product_search_service.RemoveProductFromProductSetRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, + 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 @@ -904,18 +969,23 @@ def list_products_in_product_set(self) -> Callable[ # 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', - request_serializer=product_search_service.ListProductsInProductSetRequest.serialize, - response_deserializer=product_search_service.ListProductsInProductSetResponse.deserialize, + 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 @@ -941,18 +1011,21 @@ def import_product_sets(self) -> Callable[ # 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 @@ -993,16 +1066,16 @@ def purge_products(self) -> Callable[ # 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, @@ -1010,8 +1083,7 @@ 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, @@ -1083,8 +1155,7 @@ 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,8 +1227,7 @@ 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, @@ -1259,8 +1329,7 @@ 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, @@ -1272,8 +1341,7 @@ 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, @@ -1302,8 +1370,7 @@ 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 @@ -1317,6 +1384,4 @@ 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 e3767dd63b7d..aac463001e61 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,34 +13,29 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import logging -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 retry as retries -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 json # type: ignore +import logging import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +from requests import __version__ as requests_version +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_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.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 google.protobuf import ( + empty_pb2, # type: ignore + json_format, +) - -from .rest_base import _BaseProductSearchRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseProductSearchRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -49,6 +44,7 @@ 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 @@ -217,7 +213,15 @@ 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 @@ -225,7 +229,14 @@ def pre_add_product_to_product_set(self, request: product_search_service.AddProd """ 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 @@ -233,7 +244,9 @@ def pre_create_product(self, request: product_search_service.CreateProductReques """ 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` @@ -246,7 +259,11 @@ def post_create_product(self, response: product_search_service.Product) -> produ """ 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 @@ -261,7 +278,14 @@ def post_create_product_with_metadata(self, response: product_search_service.Pro """ 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 @@ -269,7 +293,9 @@ def pre_create_product_set(self, request: product_search_service.CreateProductSe """ 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` @@ -282,7 +308,13 @@ def post_create_product_set(self, response: product_search_service.ProductSet) - """ 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 @@ -297,7 +329,14 @@ def post_create_product_set_with_metadata(self, response: product_search_service """ 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 @@ -305,7 +344,9 @@ def pre_create_reference_image(self, request: product_search_service.CreateRefer """ 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` @@ -318,7 +359,13 @@ def post_create_reference_image(self, response: product_search_service.Reference """ 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 @@ -333,7 +380,14 @@ def post_create_reference_image_with_metadata(self, response: product_search_ser """ 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 @@ -341,7 +395,14 @@ def pre_delete_product(self, request: product_search_service.DeleteProductReques """ 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 @@ -349,7 +410,14 @@ def pre_delete_product_set(self, request: product_search_service.DeleteProductSe """ 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 @@ -357,7 +425,14 @@ def pre_delete_reference_image(self, request: product_search_service.DeleteRefer """ 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 @@ -365,7 +440,9 @@ def pre_get_product(self, request: product_search_service.GetProductRequest, met """ 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` @@ -378,7 +455,11 @@ def post_get_product(self, response: product_search_service.Product) -> 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 @@ -393,7 +474,14 @@ def post_get_product_with_metadata(self, response: product_search_service.Produc """ 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 @@ -401,7 +489,9 @@ def pre_get_product_set(self, request: product_search_service.GetProductSetReque """ 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` @@ -414,7 +504,13 @@ def post_get_product_set(self, response: product_search_service.ProductSet) -> p """ 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 @@ -429,7 +525,14 @@ def post_get_product_set_with_metadata(self, response: product_search_service.Pr """ 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 @@ -437,7 +540,9 @@ def pre_get_reference_image(self, request: product_search_service.GetReferenceIm """ 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` @@ -450,7 +555,13 @@ def post_get_reference_image(self, response: product_search_service.ReferenceIma """ 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 @@ -465,7 +576,14 @@ def post_get_reference_image_with_metadata(self, response: product_search_servic """ 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 @@ -473,7 +591,9 @@ def pre_import_product_sets(self, request: product_search_service.ImportProductS """ 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` @@ -486,7 +606,11 @@ def post_import_product_sets(self, response: operations_pb2.Operation) -> operat """ 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 @@ -501,7 +625,14 @@ def post_import_product_sets_with_metadata(self, response: operations_pb2.Operat """ 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 @@ -509,7 +640,9 @@ def pre_list_products(self, request: product_search_service.ListProductsRequest, """ 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` @@ -522,7 +655,14 @@ def post_list_products(self, response: product_search_service.ListProductsRespon """ 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 @@ -537,7 +677,14 @@ def post_list_products_with_metadata(self, response: product_search_service.List """ 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 @@ -545,7 +692,9 @@ def pre_list_product_sets(self, request: product_search_service.ListProductSetsR """ 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` @@ -558,7 +707,14 @@ def post_list_product_sets(self, response: product_search_service.ListProductSet """ 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 @@ -573,7 +729,14 @@ def post_list_product_sets_with_metadata(self, response: product_search_service. """ 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 @@ -581,7 +744,9 @@ def pre_list_products_in_product_set(self, request: product_search_service.ListP """ 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` @@ -594,7 +759,14 @@ def post_list_products_in_product_set(self, response: product_search_service.Lis """ 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 @@ -609,7 +781,14 @@ def post_list_products_in_product_set_with_metadata(self, response: product_sear """ 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 @@ -617,7 +796,9 @@ def pre_list_reference_images(self, request: product_search_service.ListReferenc """ 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` @@ -630,7 +811,14 @@ def post_list_reference_images(self, response: product_search_service.ListRefere """ 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 @@ -645,7 +833,14 @@ def post_list_reference_images_with_metadata(self, response: product_search_serv """ 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 @@ -653,7 +848,9 @@ def pre_purge_products(self, request: product_search_service.PurgeProductsReques """ 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` @@ -666,7 +863,11 @@ def post_purge_products(self, response: operations_pb2.Operation) -> operations_ """ 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 @@ -681,7 +882,14 @@ def post_purge_products_with_metadata(self, response: operations_pb2.Operation, """ 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 @@ -689,7 +897,14 @@ def pre_remove_product_from_product_set(self, request: product_search_service.Re """ 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 @@ -697,7 +912,9 @@ def pre_update_product(self, request: product_search_service.UpdateProductReques """ 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` @@ -710,7 +927,11 @@ def post_update_product(self, response: product_search_service.Product) -> produ """ 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 @@ -725,7 +946,14 @@ def post_update_product_with_metadata(self, response: product_search_service.Pro """ 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 @@ -733,7 +961,9 @@ def pre_update_product_set(self, request: product_search_service.UpdateProductSe """ 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` @@ -746,7 +976,13 @@ def post_update_product_set(self, response: product_search_service.ProductSet) - """ 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 @@ -762,8 +998,12 @@ def post_update_product_set_with_metadata(self, response: product_search_service 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 @@ -819,20 +1059,21 @@ 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: @@ -876,10 +1117,11 @@ def __init__(self, *, 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) @@ -896,40 +1138,46 @@ 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") @@ -941,69 +1189,83 @@ 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() - 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, @@ -1012,14 +1274,24 @@ def __call__(self, ) # 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") @@ -1031,27 +1303,29 @@ 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: @@ -1070,32 +1344,44 @@ def __call__(self, 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, @@ -1104,7 +1390,15 @@ def __call__(self, ) # 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. @@ -1119,20 +1413,24 @@ def __call__(self, 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"], @@ -1141,7 +1439,9 @@ def __call__(self, ) return resp - class _CreateProductSet(_BaseProductSearchRestTransport._BaseCreateProductSet, ProductSearchRestStub): + class _CreateProductSet( + _BaseProductSearchRestTransport._BaseCreateProductSet, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.CreateProductSet") @@ -1153,27 +1453,29 @@ 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: @@ -1199,30 +1501,42 @@ def __call__(self, 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, @@ -1231,7 +1545,15 @@ def __call__(self, ) # 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. @@ -1246,20 +1568,26 @@ def __call__(self, 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"], @@ -1268,7 +1596,9 @@ def __call__(self, ) return resp - class _CreateReferenceImage(_BaseProductSearchRestTransport._BaseCreateReferenceImage, ProductSearchRestStub): + class _CreateReferenceImage( + _BaseProductSearchRestTransport._BaseCreateReferenceImage, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.CreateReferenceImage") @@ -1280,27 +1610,29 @@ 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: @@ -1323,30 +1655,42 @@ def __call__(self, 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, @@ -1355,7 +1699,15 @@ def __call__(self, ) # 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. @@ -1370,20 +1722,26 @@ def __call__(self, 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"], @@ -1392,7 +1750,9 @@ def __call__(self, ) return resp - class _DeleteProduct(_BaseProductSearchRestTransport._BaseDeleteProduct, ProductSearchRestStub): + class _DeleteProduct( + _BaseProductSearchRestTransport._BaseDeleteProduct, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.DeleteProduct") @@ -1404,26 +1764,28 @@ 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: @@ -1438,30 +1800,40 @@ def __call__(self, 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, @@ -1470,14 +1842,23 @@ def __call__(self, ) # 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") @@ -1489,26 +1870,28 @@ 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: @@ -1525,28 +1908,38 @@ def __call__(self, 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, @@ -1555,14 +1948,23 @@ def __call__(self, ) # 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") @@ -1574,26 +1976,28 @@ 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: @@ -1610,28 +2014,38 @@ def __call__(self, 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, @@ -1640,14 +2054,23 @@ def __call__(self, ) # 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") @@ -1659,26 +2082,28 @@ 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: @@ -1697,30 +2122,44 @@ def __call__(self, 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, @@ -1729,7 +2168,14 @@ def __call__(self, ) # 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. @@ -1744,20 +2190,24 @@ def __call__(self, 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"], @@ -1766,7 +2216,9 @@ def __call__(self, ) return resp - class _GetProductSet(_BaseProductSearchRestTransport._BaseGetProductSet, ProductSearchRestStub): + class _GetProductSet( + _BaseProductSearchRestTransport._BaseGetProductSet, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.GetProductSet") @@ -1778,26 +2230,28 @@ 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: @@ -1821,30 +2275,40 @@ def __call__(self, """ - 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, @@ -1853,7 +2317,14 @@ def __call__(self, ) # 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. @@ -1868,20 +2339,26 @@ def __call__(self, 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"], @@ -1890,7 +2367,9 @@ def __call__(self, ) return resp - class _GetReferenceImage(_BaseProductSearchRestTransport._BaseGetReferenceImage, ProductSearchRestStub): + class _GetReferenceImage( + _BaseProductSearchRestTransport._BaseGetReferenceImage, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.GetReferenceImage") @@ -1902,26 +2381,28 @@ 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: @@ -1944,28 +2425,38 @@ def __call__(self, 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, @@ -1974,7 +2465,14 @@ def __call__(self, ) # 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. @@ -1989,20 +2487,26 @@ def __call__(self, 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"], @@ -2011,7 +2515,9 @@ def __call__(self, ) return resp - class _ImportProductSets(_BaseProductSearchRestTransport._BaseImportProductSets, ProductSearchRestStub): + class _ImportProductSets( + _BaseProductSearchRestTransport._BaseImportProductSets, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.ImportProductSets") @@ -2023,27 +2529,29 @@ 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: @@ -2067,30 +2575,42 @@ def __call__(self, 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, @@ -2099,7 +2619,15 @@ def __call__(self, ) # 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. @@ -2112,20 +2640,24 @@ def __call__(self, 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"], @@ -2134,7 +2666,9 @@ def __call__(self, ) return resp - class _ListProducts(_BaseProductSearchRestTransport._BaseListProducts, ProductSearchRestStub): + class _ListProducts( + _BaseProductSearchRestTransport._BaseListProducts, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.ListProducts") @@ -2146,26 +2680,28 @@ 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: @@ -2184,30 +2720,40 @@ def __call__(self, 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, @@ -2216,7 +2762,14 @@ def __call__(self, ) # 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. @@ -2231,20 +2784,26 @@ def __call__(self, 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"], @@ -2253,7 +2812,9 @@ def __call__(self, ) return resp - class _ListProductSets(_BaseProductSearchRestTransport._BaseListProductSets, ProductSearchRestStub): + class _ListProductSets( + _BaseProductSearchRestTransport._BaseListProductSets, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.ListProductSets") @@ -2265,26 +2826,28 @@ 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: @@ -2303,30 +2866,42 @@ def __call__(self, 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, @@ -2335,7 +2910,14 @@ def __call__(self, ) # 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. @@ -2350,20 +2932,26 @@ def __call__(self, 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"], @@ -2372,7 +2960,10 @@ def __call__(self, ) return resp - class _ListProductsInProductSet(_BaseProductSearchRestTransport._BaseListProductsInProductSet, ProductSearchRestStub): + class _ListProductsInProductSet( + _BaseProductSearchRestTransport._BaseListProductsInProductSet, + ProductSearchRestStub, + ): def __hash__(self): return hash("ProductSearchRestTransport.ListProductsInProductSet") @@ -2384,72 +2975,84 @@ 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() - 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, @@ -2458,7 +3061,16 @@ def __call__(self, ) # 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. @@ -2473,20 +3085,28 @@ def __call__(self, 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"], @@ -2495,7 +3115,9 @@ def __call__(self, ) return resp - class _ListReferenceImages(_BaseProductSearchRestTransport._BaseListReferenceImages, ProductSearchRestStub): + class _ListReferenceImages( + _BaseProductSearchRestTransport._BaseListReferenceImages, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.ListReferenceImages") @@ -2507,26 +3129,28 @@ 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: @@ -2547,28 +3171,38 @@ def __call__(self, 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, @@ -2577,7 +3211,14 @@ def __call__(self, ) # 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. @@ -2592,20 +3233,28 @@ def __call__(self, 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"], @@ -2614,7 +3263,9 @@ def __call__(self, ) return resp - class _PurgeProducts(_BaseProductSearchRestTransport._BasePurgeProducts, ProductSearchRestStub): + class _PurgeProducts( + _BaseProductSearchRestTransport._BasePurgeProducts, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.PurgeProducts") @@ -2626,27 +3277,29 @@ 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: @@ -2668,32 +3321,44 @@ def __call__(self, """ - 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, @@ -2702,7 +3367,15 @@ def __call__(self, ) # 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. @@ -2715,20 +3388,24 @@ def __call__(self, 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"], @@ -2737,7 +3414,10 @@ def __call__(self, ) return resp - class _RemoveProductFromProductSet(_BaseProductSearchRestTransport._BaseRemoveProductFromProductSet, ProductSearchRestStub): + class _RemoveProductFromProductSet( + _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet, + ProductSearchRestStub, + ): def __hash__(self): return hash("ProductSearchRestTransport.RemoveProductFromProductSet") @@ -2749,69 +3429,83 @@ 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() - 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, @@ -2820,14 +3514,26 @@ def __call__(self, ) # 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") @@ -2839,27 +3545,29 @@ 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: @@ -2878,32 +3586,44 @@ def __call__(self, 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, @@ -2912,7 +3632,15 @@ def __call__(self, ) # 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. @@ -2927,20 +3655,24 @@ def __call__(self, 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"], @@ -2949,7 +3681,9 @@ def __call__(self, ) return resp - class _UpdateProductSet(_BaseProductSearchRestTransport._BaseUpdateProductSet, ProductSearchRestStub): + class _UpdateProductSet( + _BaseProductSearchRestTransport._BaseUpdateProductSet, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.UpdateProductSet") @@ -2961,27 +3695,29 @@ 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: @@ -3007,30 +3743,42 @@ def __call__(self, 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, @@ -3039,7 +3787,15 @@ def __call__(self, ) # 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. @@ -3054,20 +3810,26 @@ def __call__(self, 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"], @@ -3077,162 +3839,212 @@ def __call__(self, 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") @@ -3244,27 +4056,28 @@ 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: @@ -3282,30 +4095,40 @@ def __call__(self, 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, @@ -3314,7 +4137,14 @@ def __call__(self, ) # 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. @@ -3325,19 +4155,21 @@ def __call__(self, 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, @@ -3354,6 +4186,4 @@ 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 9a86ad652029..4cb9977b5a74 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,19 +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 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.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 google.protobuf import ( + empty_pb2, # type: ignore + json_format, +) + +from .base import DEFAULT_CLIENT_INFO, ProductSearchTransport class _BaseProductSearchRestTransport(ProductSearchTransport): @@ -42,14 +41,16 @@ 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,7 +74,9 @@ def __init__(self, *, # 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,33 +87,39 @@ def __init__(self, *, 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 @@ -119,17 +128,23 @@ 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 @@ -138,20 +153,24 @@ 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 @@ -166,17 +185,23 @@ 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 @@ -185,20 +210,24 @@ 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 @@ -213,17 +242,23 @@ 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 @@ -232,20 +267,24 @@ 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 @@ -260,17 +299,23 @@ 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 @@ -279,19 +324,23 @@ 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 @@ -303,11 +352,17 @@ 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 @@ -316,19 +371,23 @@ 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 @@ -340,11 +399,17 @@ 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 @@ -353,19 +418,23 @@ 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 @@ -377,11 +446,17 @@ 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 @@ -390,19 +465,23 @@ 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 @@ -414,11 +493,17 @@ 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 @@ -427,19 +512,23 @@ 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 @@ -451,11 +540,17 @@ 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 @@ -464,19 +559,23 @@ 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 @@ -488,11 +587,17 @@ 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 @@ -501,20 +606,24 @@ 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 @@ -529,17 +638,23 @@ 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 @@ -548,19 +663,23 @@ 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 @@ -572,11 +691,17 @@ 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 @@ -585,19 +710,23 @@ 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 @@ -609,11 +738,17 @@ 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 @@ -622,35 +757,47 @@ 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 @@ -659,19 +806,23 @@ 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 @@ -683,11 +834,17 @@ 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 @@ -696,20 +853,24 @@ 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 @@ -724,17 +885,23 @@ 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 @@ -743,26 +910,32 @@ 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 @@ -771,17 +944,23 @@ 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 @@ -790,20 +969,24 @@ 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 @@ -818,17 +1001,23 @@ 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 @@ -837,20 +1026,24 @@ 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 @@ -865,17 +1058,23 @@ 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 @@ -886,38 +1085,36 @@ 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 2b5430e8fc17..bd9c22403b9f 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 @@ -51,6 +51,7 @@ ImageSource, InputConfig, LatLongRect, + Likelihood, LocalizedObjectAnnotation, LocationInfo, OperationMetadata, @@ -59,7 +60,6 @@ SafeSearchAnnotation, TextDetectionParams, WebDetectionParams, - Likelihood, ) from .product_search import ( ProductSearchParams, @@ -111,88 +111,88 @@ ) __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 f848fc78244f..2980098d1d67 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,14 +19,13 @@ 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", }, ) @@ -85,15 +84,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 71c9882cd43b..f001daa78ca3 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 @@ -19,59 +19,58 @@ 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 geometry, product_search, 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 - +from google.type import ( + color_pb2, # type: ignore + latlng_pb2, # type: ignore +) __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", }, ) @@ -94,6 +93,7 @@ class Likelihood(proto.Enum): VERY_LIKELY (5): It is very likely. """ + UNKNOWN = 0 VERY_UNLIKELY = 1 UNLIKELY = 2 @@ -121,6 +121,7 @@ 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. @@ -159,6 +160,7 @@ class Type(proto.Enum): OBJECT_LOCALIZATION (19): Run localizer for object detection. """ + TYPE_UNSPECIFIED = 0 FACE_DETECTION = 1 LANDMARK_DETECTION = 2 @@ -256,10 +258,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", ) @@ -328,6 +330,7 @@ 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 @@ -411,6 +414,7 @@ class Type(proto.Enum): RIGHT_CHEEK_CENTER (36): Right cheek center. """ + UNKNOWN_LANDMARK = 0 LEFT_EYE = 1 RIGHT_EYE = 2 @@ -449,10 +453,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, @@ -495,40 +499,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", ) @@ -647,15 +651,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", ) @@ -733,30 +737,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", ) @@ -820,10 +824,10 @@ class DominantColorsAnnotation(proto.Message): fraction. """ - colors: MutableSequence['ColorInfo'] = proto.RepeatedField( + colors: MutableSequence["ColorInfo"] = proto.RepeatedField( proto.MESSAGE, number=1, - message='ColorInfo', + message="ColorInfo", ) @@ -836,10 +840,10 @@ class ImageProperties(proto.Message): successfully. """ - dominant_colors: 'DominantColorsAnnotation' = proto.Field( + dominant_colors: "DominantColorsAnnotation" = proto.Field( proto.MESSAGE, number=1, - message='DominantColorsAnnotation', + message="DominantColorsAnnotation", ) @@ -883,10 +887,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", ) @@ -983,34 +987,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", ) @@ -1029,20 +1033,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", ) @@ -1122,55 +1126,57 @@ 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( - proto.MESSAGE, - number=22, - message='LocalizedObjectAnnotation', + localized_object_annotations: MutableSequence["LocalizedObjectAnnotation"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=22, + 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, @@ -1187,10 +1193,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", ) @@ -1226,10 +1232,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, @@ -1251,10 +1257,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", ) @@ -1290,20 +1296,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, @@ -1331,15 +1337,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, @@ -1386,10 +1392,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, @@ -1413,10 +1419,10 @@ class BatchAnnotateFilesResponse(proto.Message): BatchAnnotateFilesRequest. """ - responses: MutableSequence['AnnotateFileResponse'] = proto.RepeatedField( + responses: MutableSequence["AnnotateFileResponse"] = proto.RepeatedField( proto.MESSAGE, number=1, - message='AnnotateFileResponse', + message="AnnotateFileResponse", ) @@ -1436,25 +1442,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", ) @@ -1467,10 +1473,10 @@ class AsyncAnnotateFileResponse(proto.Message): AsyncAnnotateFileRequest. """ - output_config: 'OutputConfig' = proto.Field( + output_config: "OutputConfig" = proto.Field( proto.MESSAGE, number=1, - message='OutputConfig', + message="OutputConfig", ) @@ -1508,15 +1514,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, @@ -1538,10 +1544,10 @@ class AsyncBatchAnnotateImagesResponse(proto.Message): AsyncBatchAnnotateImagesRequest. """ - output_config: 'OutputConfig' = proto.Field( + output_config: "OutputConfig" = proto.Field( proto.MESSAGE, number=1, - message='OutputConfig', + message="OutputConfig", ) @@ -1577,10 +1583,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, @@ -1603,10 +1609,10 @@ class AsyncBatchAnnotateFilesResponse(proto.Message): AsyncBatchAnnotateFilesRequest. """ - responses: MutableSequence['AsyncAnnotateFileResponse'] = proto.RepeatedField( + responses: MutableSequence["AsyncAnnotateFileResponse"] = proto.RepeatedField( proto.MESSAGE, number=1, - message='AsyncAnnotateFileResponse', + message="AsyncAnnotateFileResponse", ) @@ -1631,10 +1637,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, @@ -1667,10 +1673,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, @@ -1747,6 +1753,7 @@ class OperationMetadata(proto.Message): The time when the operation result was last updated. """ + class State(proto.Enum): r"""Batch operation states. @@ -1762,6 +1769,7 @@ class State(proto.Enum): CANCELLED (4): The batch processing was cancelled. """ + STATE_UNSPECIFIED = 0 CREATED = 1 RUNNING = 2 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 e490d3aa3089..f0299458bc05 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 @@ -19,16 +19,14 @@ import proto # type: ignore -from google.cloud.vision_v1.types import geometry -from google.cloud.vision_v1.types import product_search_service +from google.cloud.vision_v1.types import geometry, 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", }, ) @@ -196,15 +194,17 @@ 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( - proto.MESSAGE, - number=3, - message='ProductSearchResults.ObjectAnnotation', + object_annotations: MutableSequence["ProductSearchResults.ObjectAnnotation"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=3, + 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 b07103c83a0c..71c64951e4e2 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 @@ -20,45 +20,46 @@ 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.protobuf import ( + field_mask_pb2, # type: ignore + timestamp_pb2, # type: ignore +) from google.rpc import status_pb2 # type: ignore - __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", }, ) @@ -277,10 +278,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, @@ -335,10 +336,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, @@ -378,10 +379,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, @@ -430,10 +431,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, @@ -488,10 +489,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, @@ -530,10 +531,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, @@ -584,10 +585,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, @@ -648,10 +649,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, @@ -800,10 +801,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, @@ -912,11 +913,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", ) @@ -938,10 +939,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", ) @@ -967,10 +968,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, @@ -997,6 +998,7 @@ 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. @@ -1019,6 +1021,7 @@ class State(proto.Enum): processed before the cancel command are output as specified in the request. """ + STATE_UNSPECIFIED = 0 PROCESSING = 1 SUCCESSFUL = 2 @@ -1090,16 +1093,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 f1d19b2888a9..59a288e308a1 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,16 +21,15 @@ 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", }, ) @@ -82,6 +81,7 @@ 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. @@ -101,6 +101,7 @@ class BreakType(proto.Enum): LINE_BREAK (5): Line break that ends a paragraph. """ + UNKNOWN = 0 SPACE = 1 SURE_SPACE = 2 @@ -108,10 +109,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,21 +130,23 @@ class TextProperty(proto.Message): Detected start or end of a text segment. """ - detected_languages: MutableSequence['TextAnnotation.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TextAnnotation.DetectedLanguage', + detected_languages: MutableSequence["TextAnnotation.DetectedLanguage"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + 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 +173,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 +186,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, @@ -235,6 +238,7 @@ 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. @@ -252,6 +256,7 @@ class BlockType(proto.Enum): BARCODE (5): Barcode block. """ + UNKNOWN = 0 TEXT = 1 TABLE = 2 @@ -259,20 +264,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, @@ -312,20 +317,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, @@ -359,20 +364,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, @@ -406,10 +411,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 9fca05e563e0..ac19ca90ff8d 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,11 +19,10 @@ import proto # type: ignore - __protobuf__ = proto.module( - package='google.cloud.vision.v1', + package="google.cloud.vision.v1", manifest={ - 'WebDetection', + "WebDetection", }, ) @@ -138,15 +137,19 @@ class WebPage(proto.Message): proto.STRING, number=3, ) - full_matching_images: MutableSequence['WebDetection.WebImage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='WebDetection.WebImage', + full_matching_images: MutableSequence["WebDetection.WebImage"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=4, + message="WebDetection.WebImage", + ) ) - partial_matching_images: MutableSequence['WebDetection.WebImage'] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='WebDetection.WebImage', + partial_matching_images: MutableSequence["WebDetection.WebImage"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=5, + 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 dc578ce2e643..e5a365361f11 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from google.cloud.vision_v1p1beta1 import gapic_version as package_version +import sys import google.api_core as api_core -import sys +from google.cloud.vision_v1p1beta1 import gapic_version as package_version __version__ = package_version.__version__ @@ -28,70 +28,69 @@ import importlib_metadata as metadata -from .services.image_annotator import ImageAnnotatorClient -from .services.image_annotator import ImageAnnotatorAsyncClient - -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 .services.image_annotator import ImageAnnotatorAsyncClient, ImageAnnotatorClient +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.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 warnings import sys + import warnings _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. @@ -129,60 +128,64 @@ 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/") + 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 b1663fdd632d..c7f40549e472 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 .client import ImageAnnotatorClient from .async_client import ImageAnnotatorAsyncClient +from .client import ImageAnnotatorClient __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 b19bdef55058..fa34dcaba361 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 @@ -14,20 +14,29 @@ # limitations under the License. # import logging as std_logging -from collections import OrderedDict import re -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 collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) -from google.api_core.client_options import ClientOptions +import google.protobuf 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.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.vision_v1p1beta1 import gapic_version as package_version +from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -35,18 +44,21 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.cloud.vision_v1p1beta1.types import image_annotator -from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport + from .client import ImageAnnotatorClient +from .transports.base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport 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 @@ -63,16 +75,30 @@ 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): @@ -87,7 +113,9 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ImageAnnotatorAsyncClient: The constructed client. """ - return ImageAnnotatorClient.from_service_account_info.__func__(ImageAnnotatorAsyncClient, info, *args, **kwargs) # type: ignore + return ImageAnnotatorClient.from_service_account_info.__func__( + ImageAnnotatorAsyncClient, info, *args, **kwargs + ) # type: ignore @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -103,12 +131,16 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ImageAnnotatorAsyncClient: The constructed client. """ - return ImageAnnotatorClient.from_service_account_file.__func__(ImageAnnotatorAsyncClient, filename, *args, **kwargs) # type: ignore + return ImageAnnotatorClient.from_service_account_file.__func__( + ImageAnnotatorAsyncClient, filename, *args, **kwargs + ) # type: ignore 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: @@ -171,12 +203,16 @@ 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: @@ -231,31 +267,43 @@ def __init__(self, *, 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. @@ -313,10 +361,14 @@ 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. @@ -330,7 +382,9 @@ 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() @@ -352,12 +406,13 @@ 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__) -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +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__ = ( - "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 da22815ef5b9..5c4c76ebb374 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 @@ -13,27 +13,38 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict -from http import HTTPStatus import json import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) -from google.cloud.vision_v1p1beta1 import gapic_version as package_version - +import google.protobuf 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.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.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.cloud.vision_v1p1beta1 import gapic_version as package_version +from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -42,6 +53,7 @@ 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 @@ -49,7 +61,8 @@ _LOGGER = std_logging.getLogger(__name__) from google.cloud.vision_v1p1beta1.types import image_annotator -from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO + +from .transports.base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport from .transports.grpc import ImageAnnotatorGrpcTransport from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport from .transports.rest import ImageAnnotatorRestTransport @@ -62,14 +75,16 @@ class ImageAnnotatorClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _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: @@ -145,14 +160,16 @@ 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" @@ -191,8 +208,7 @@ 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) @@ -209,62 +225,86 @@ 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: @@ -296,14 +336,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio 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 @@ -316,7 +360,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # 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 @@ -341,7 +387,9 @@ 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 @@ -364,7 +412,9 @@ 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: @@ -380,17 +430,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ 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: @@ -426,15 +484,18 @@ 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 @@ -467,12 +528,16 @@ 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: @@ -527,14 +592,22 @@ def __init__(self, *, 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 @@ -545,7 +618,9 @@ def __init__(self, *, 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 @@ -554,30 +629,40 @@ def __init__(self, *, 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 " - "directly." + "When providing a transport instance, provide its scopes directly." ) 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) @@ -596,28 +681,41 @@ def __init__(self, *, ) 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. @@ -675,10 +773,14 @@ 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. @@ -721,16 +823,11 @@ 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 d3a583db5759..1de28b3fb87a 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,20 +19,18 @@ from .base import ImageAnnotatorTransport from .grpc import ImageAnnotatorGrpcTransport from .grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport -from .rest import ImageAnnotatorRestTransport -from .rest import ImageAnnotatorRestInterceptor - +from .rest import ImageAnnotatorRestInterceptor, ImageAnnotatorRestTransport # 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 ee5cc98433e8..e2f38d4464cf 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,20 +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 +import google.auth # type: ignore +import google.protobuf 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.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 +from google.oauth2 import service_account # 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__ @@ -39,24 +39,25 @@ 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: @@ -91,31 +92,43 @@ 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=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + 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=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + 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 @@ -140,24 +153,27 @@ 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 @@ -165,6 +181,4 @@ 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 d0df4cbf82b2..c49deb3423bd 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 @@ -19,22 +19,22 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union -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 +import google.auth # type: ignore +import google.protobuf.message +from google.api_core import gapic_v1, grpc_helpers +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore from google.cloud.vision_v1p1beta1.types import image_annotator -from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO +from google.protobuf.json_format import MessageToJson + +from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport 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,7 +44,9 @@ 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): @@ -65,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.v1p1beta1.ImageAnnotator", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -76,7 +78,11 @@ 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) @@ -91,7 +97,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, @@ -116,23 +122,26 @@ 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: @@ -255,19 +264,23 @@ def __init__(self, *, ) 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. @@ -303,19 +316,21 @@ def create_channel(cls, 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 @@ -331,13 +346,13 @@ def batch_annotate_images(self) -> Callable[ # 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() @@ -347,6 +362,4 @@ 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 999942d0ebea..b776a949834b 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 pickle import logging as std_logging +import pickle 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 +import grpc # type: ignore +import proto # type: ignore +from grpc.experimental import aio # type: ignore + +import google.protobuf.message 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.cloud.vision_v1p1beta1.types import image_annotator from google.protobuf.json_format import MessageToJson -import google.protobuf.message -import grpc # type: ignore -import proto # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.vision_v1p1beta1.types import image_annotator -from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO +from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport 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,9 +46,13 @@ _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): @@ -69,7 +73,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, @@ -80,7 +84,11 @@ 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) @@ -95,7 +103,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, @@ -125,13 +133,15 @@ 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. @@ -162,24 +172,26 @@ def create_channel(cls, 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: @@ -304,7 +316,9 @@ def __init__(self, *, 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) @@ -319,9 +333,12 @@ 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 @@ -337,16 +354,16 @@ def batch_annotate_images(self) -> Callable[ # 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, @@ -378,6 +395,4 @@ 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 75fc4c20c3f6..8b9175abb29e 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,31 +13,25 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import logging -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 retry as retries -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 json # type: ignore +import logging import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +from requests import __version__ as requests_version +import google.protobuf +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.cloud.vision_v1p1beta1.types import image_annotator +from google.protobuf import json_format - -from .rest_base import _BaseImageAnnotatorRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseImageAnnotatorRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -46,6 +40,7 @@ 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 @@ -90,7 +85,15 @@ 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 @@ -98,7 +101,9 @@ def pre_batch_annotate_images(self, request: image_annotator.BatchAnnotateImages """ 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` @@ -111,7 +116,14 @@ def post_batch_annotate_images(self, response: image_annotator.BatchAnnotateImag """ 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 @@ -149,20 +161,21 @@ 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: @@ -206,16 +219,20 @@ def __init__(self, *, 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") @@ -227,27 +244,29 @@ 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: @@ -271,30 +290,42 @@ def __call__(self, 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, @@ -303,7 +334,15 @@ def __call__(self, ) # 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. @@ -318,20 +357,26 @@ def __call__(self, 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"], @@ -341,12 +386,15 @@ def __call__(self, 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: @@ -356,6 +404,4 @@ 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 09b70d889133..7afe90a2d4e3 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,17 +14,14 @@ # 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.cloud.vision_v1p1beta1.types import image_annotator +from google.protobuf import json_format + +from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport class _BaseImageAnnotatorRestTransport(ImageAnnotatorTransport): @@ -40,14 +37,16 @@ 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,7 +70,9 @@ def __init__(self, *, # 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() @@ -82,27 +83,31 @@ def __init__(self, *, 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 @@ -117,22 +122,26 @@ 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 731d736166eb..59f5c671e0d1 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 @@ -36,12 +36,12 @@ ImageProperties, ImageSource, LatLongRect, + Likelihood, LocationInfo, Property, SafeSearchAnnotation, TextDetectionParams, WebDetectionParams, - Likelihood, ) from .text_annotation import ( Block, @@ -56,37 +56,37 @@ ) __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 044076dad07e..47caffc618a5 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,13 +19,12 @@ import proto # type: ignore - __protobuf__ = proto.module( - package='google.cloud.vision.v1p1beta1', + package="google.cloud.vision.v1p1beta1", manifest={ - 'Vertex', - 'BoundingPoly', - 'Position', + "Vertex", + "BoundingPoly", + "Position", }, ) @@ -60,10 +59,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 80e8feadba5d..1d6547995bfa 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 @@ -19,40 +19,40 @@ 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 geometry, 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 - +from google.type import ( + color_pb2, # type: ignore + latlng_pb2, # type: ignore +) __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", }, ) @@ -80,6 +80,7 @@ class Likelihood(proto.Enum): It is very likely that the image belongs to the specified vertical. """ + UNKNOWN = 0 VERY_UNLIKELY = 1 UNLIKELY = 2 @@ -107,6 +108,7 @@ 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. @@ -137,6 +139,7 @@ class Type(proto.Enum): WEB_DETECTION (10): Run web detection. """ + TYPE_UNSPECIFIED = 0 FACE_DETECTION = 1 LANDMARK_DETECTION = 2 @@ -218,10 +221,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", ) @@ -291,6 +294,7 @@ 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 @@ -370,6 +374,7 @@ class Type(proto.Enum): CHIN_RIGHT_GONION (34): Chin right gonion. """ + UNKNOWN_LANDMARK = 0 LEFT_EYE = 1 RIGHT_EYE = 2 @@ -406,10 +411,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 +457,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 +608,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 +649,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 +736,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 +752,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 +799,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 +893,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 +933,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 +992,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 +1059,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 +1075,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 2a88de5c5d42..a419cae40f21 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,16 +21,15 @@ 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", }, ) @@ -82,6 +81,7 @@ 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. @@ -101,6 +101,7 @@ class BreakType(proto.Enum): LINE_BREAK (5): Line break that ends a paragraph. """ + UNKNOWN = 0 SPACE = 1 SURE_SPACE = 2 @@ -108,10 +109,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,21 +130,23 @@ class TextProperty(proto.Message): Detected start or end of a text segment. """ - detected_languages: MutableSequence['TextAnnotation.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TextAnnotation.DetectedLanguage', + detected_languages: MutableSequence["TextAnnotation.DetectedLanguage"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + 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, @@ -168,10 +171,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, @@ -181,10 +184,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, @@ -220,6 +223,7 @@ 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. @@ -237,6 +241,7 @@ class BlockType(proto.Enum): BARCODE (5): Barcode block. """ + UNKNOWN = 0 TEXT = 1 TABLE = 2 @@ -244,20 +249,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, @@ -297,20 +302,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, @@ -344,20 +349,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, @@ -391,10 +396,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 286fb9ef4fb6..2924fbd3cf5d 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,11 +19,10 @@ import proto # type: ignore - __protobuf__ = proto.module( - package='google.cloud.vision.v1p1beta1', + package="google.cloud.vision.v1p1beta1", manifest={ - 'WebDetection', + "WebDetection", }, ) @@ -136,15 +135,19 @@ class WebPage(proto.Message): proto.STRING, number=3, ) - full_matching_images: MutableSequence['WebDetection.WebImage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='WebDetection.WebImage', + full_matching_images: MutableSequence["WebDetection.WebImage"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=4, + message="WebDetection.WebImage", + ) ) - partial_matching_images: MutableSequence['WebDetection.WebImage'] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='WebDetection.WebImage', + partial_matching_images: MutableSequence["WebDetection.WebImage"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=5, + 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 ad6f9a79441a..06d169afc46a 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from google.cloud.vision_v1p2beta1 import gapic_version as package_version +import sys import google.api_core as api_core -import sys +from google.cloud.vision_v1p2beta1 import gapic_version as package_version __version__ = package_version.__version__ @@ -28,82 +28,80 @@ import importlib_metadata as metadata -from .services.image_annotator import ImageAnnotatorClient -from .services.image_annotator import ImageAnnotatorAsyncClient - -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 .services.image_annotator import ImageAnnotatorAsyncClient, ImageAnnotatorClient +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.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 warnings import sys + import warnings _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. @@ -141,72 +139,76 @@ 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/") + 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 b1663fdd632d..c7f40549e472 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 .client import ImageAnnotatorClient from .async_client import ImageAnnotatorAsyncClient +from .client import ImageAnnotatorClient __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 9a5082474f9a..62aec494d909 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 @@ -14,42 +14,56 @@ # limitations under the License. # import logging as std_logging -from collections import OrderedDict import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union import uuid +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) -from google.cloud.vision_v1p2beta1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions +import google.protobuf 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.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.vision_v1p2beta1 import gapic_version as package_version +from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore +from google.api_core import ( + operation, # type: ignore + operation_async, # type: ignore +) from google.cloud.vision_v1p2beta1.types import image_annotator -from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport + from .client import ImageAnnotatorClient +from .transports.base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport 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 @@ -66,16 +80,30 @@ 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): @@ -90,7 +118,9 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ImageAnnotatorAsyncClient: The constructed client. """ - return ImageAnnotatorClient.from_service_account_info.__func__(ImageAnnotatorAsyncClient, info, *args, **kwargs) # type: ignore + return ImageAnnotatorClient.from_service_account_info.__func__( + ImageAnnotatorAsyncClient, info, *args, **kwargs + ) # type: ignore @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -106,12 +136,16 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ImageAnnotatorAsyncClient: The constructed client. """ - return ImageAnnotatorClient.from_service_account_file.__func__(ImageAnnotatorAsyncClient, filename, *args, **kwargs) # type: ignore + return ImageAnnotatorClient.from_service_account_file.__func__( + ImageAnnotatorAsyncClient, filename, *args, **kwargs + ) # type: ignore 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: @@ -174,12 +208,16 @@ 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: @@ -234,31 +272,43 @@ def __init__(self, *, 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. @@ -316,10 +366,14 @@ 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. @@ -333,7 +387,9 @@ 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() @@ -349,14 +405,19 @@ 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 @@ -427,10 +488,14 @@ 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. @@ -444,7 +509,9 @@ 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() @@ -474,12 +541,13 @@ 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__) -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +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__ = ( - "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 b262690942b3..5eb3fe5f92ff 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 @@ -13,28 +13,39 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict -from http import HTTPStatus import json import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import uuid import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) -from google.cloud.vision_v1p2beta1 import gapic_version as package_version - +import google.protobuf 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.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.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.cloud.vision_v1p2beta1 import gapic_version as package_version +from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -43,16 +54,20 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore +from google.api_core import ( + operation, # type: ignore + operation_async, # type: ignore +) from google.cloud.vision_v1p2beta1.types import image_annotator -from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO + +from .transports.base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport from .transports.grpc import ImageAnnotatorGrpcTransport from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport from .transports.rest import ImageAnnotatorRestTransport @@ -65,14 +80,16 @@ class ImageAnnotatorClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _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: @@ -148,14 +165,16 @@ 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" @@ -194,8 +213,7 @@ 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) @@ -212,62 +230,86 @@ 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: @@ -299,14 +341,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio 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 @@ -319,7 +365,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # 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 @@ -344,7 +392,9 @@ 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 @@ -367,7 +417,9 @@ 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: @@ -383,17 +435,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ 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: @@ -429,15 +489,18 @@ 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 @@ -470,12 +533,16 @@ 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: @@ -530,14 +597,22 @@ def __init__(self, *, 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 @@ -548,7 +623,9 @@ def __init__(self, *, 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 @@ -557,30 +634,40 @@ def __init__(self, *, 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 " - "directly." + "When providing a transport instance, provide its scopes directly." ) 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) @@ -599,28 +686,41 @@ def __init__(self, *, ) 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. @@ -678,10 +778,14 @@ 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. @@ -710,14 +814,19 @@ 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 @@ -788,10 +897,14 @@ 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. @@ -804,7 +917,9 @@ 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() @@ -842,16 +957,11 @@ 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 d3a583db5759..1de28b3fb87a 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,20 +19,18 @@ from .base import ImageAnnotatorTransport from .grpc import ImageAnnotatorGrpcTransport from .grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport -from .rest import ImageAnnotatorRestTransport -from .rest import ImageAnnotatorRestInterceptor - +from .rest import ImageAnnotatorRestInterceptor, ImageAnnotatorRestTransport # 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 96a26ecc7264..f57c0cc890ce 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,21 @@ 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 +import google.auth # type: ignore +import google.protobuf from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, operations_v1 from google.api_core import retry as retries -from google.api_core import operations_v1 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 from google.cloud.vision_v1p2beta1.types import image_annotator -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # 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,24 +40,25 @@ 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: @@ -93,31 +93,43 @@ 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=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + 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=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + 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 @@ -157,14 +169,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() @@ -174,21 +186,24 @@ 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 @@ -196,6 +211,4 @@ 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 e2a668a6d116..139314c7cd35 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 @@ -19,24 +19,23 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union -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.protobuf.json_format import MessageToJson -import google.protobuf.message - import grpc # type: ignore import proto # type: ignore +import google.auth # type: ignore +import google.protobuf.message +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore from google.cloud.vision_v1p2beta1.types import image_annotator -from google.longrunning import operations_pb2 # type: ignore -from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport 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,7 +45,9 @@ 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 +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.v1p2beta1.ImageAnnotator", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -78,7 +79,11 @@ 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) @@ -93,7 +98,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, @@ -118,23 +123,26 @@ 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: @@ -258,19 +266,23 @@ def __init__(self, *, ) 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. @@ -306,13 +318,12 @@ def create_channel(cls, 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 @@ -332,9 +343,12 @@ 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 @@ -350,18 +364,20 @@ def batch_annotate_images(self) -> Callable[ # 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 @@ -382,13 +398,15 @@ def async_batch_annotate_files(self) -> Callable[ # 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', - request_serializer=image_annotator.AsyncBatchAnnotateFilesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, + 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() @@ -398,6 +416,4 @@ 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 98d2c16f8536..b8036e5f7625 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,32 +15,31 @@ # import inspect import json -import pickle import logging as std_logging +import pickle 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 +import grpc # type: ignore +import proto # type: ignore +from grpc.experimental import aio # type: ignore + +import google.protobuf.message 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.api_core import operations_v1 -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.cloud.vision_v1p2beta1.types import image_annotator +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 grpc.experimental import aio # type: ignore - -from google.cloud.vision_v1p2beta1.types import image_annotator -from google.longrunning import operations_pb2 # type: ignore -from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO +from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport 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 @@ -48,9 +47,13 @@ _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): @@ -71,7 +74,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, @@ -82,7 +85,11 @@ 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) @@ -97,7 +104,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, @@ -127,13 +134,15 @@ 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. @@ -164,24 +173,26 @@ def create_channel(cls, 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: @@ -307,7 +318,9 @@ def __init__(self, *, 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) @@ -338,9 +351,12 @@ 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 @@ -356,18 +372,21 @@ def batch_annotate_images(self) -> Callable[ # 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 @@ -388,16 +407,18 @@ def async_batch_annotate_files(self) -> Callable[ # 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', - request_serializer=image_annotator.AsyncBatchAnnotateFilesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, + 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, @@ -444,6 +465,4 @@ 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 1e04a22edf86..d523ab630811 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,33 +13,26 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import logging -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 retry as retries -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 json # type: ignore +import logging import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +from requests import __version__ as requests_version +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_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.cloud.vision_v1p2beta1.types import image_annotator from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format - -from .rest_base import _BaseImageAnnotatorRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseImageAnnotatorRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -48,6 +41,7 @@ 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 @@ -100,7 +94,15 @@ 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 @@ -108,7 +110,9 @@ def pre_async_batch_annotate_files(self, request: image_annotator.AsyncBatchAnno """ 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` @@ -121,7 +125,11 @@ def post_async_batch_annotate_files(self, response: operations_pb2.Operation) -> """ 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 @@ -136,7 +144,14 @@ def post_async_batch_annotate_files_with_metadata(self, response: operations_pb2 """ 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 @@ -144,7 +159,9 @@ def pre_batch_annotate_images(self, request: image_annotator.BatchAnnotateImages """ 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` @@ -157,7 +174,14 @@ def post_batch_annotate_images(self, response: image_annotator.BatchAnnotateImag """ 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 @@ -195,20 +219,21 @@ 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: @@ -252,10 +277,11 @@ def __init__(self, *, 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) @@ -271,23 +297,28 @@ 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") @@ -299,77 +330,91 @@ 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() - 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, @@ -378,7 +423,17 @@ def __call__(self, ) # 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. @@ -391,20 +446,24 @@ def __call__(self, 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"], @@ -413,7 +472,10 @@ def __call__(self, ) return resp - class _BatchAnnotateImages(_BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages, ImageAnnotatorRestStub): + class _BatchAnnotateImages( + _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages, + ImageAnnotatorRestStub, + ): def __hash__(self): return hash("ImageAnnotatorRestTransport.BatchAnnotateImages") @@ -425,27 +487,29 @@ 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: @@ -469,30 +533,42 @@ def __call__(self, 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, @@ -501,7 +577,15 @@ def __call__(self, ) # 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. @@ -516,20 +600,26 @@ def __call__(self, 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"], @@ -539,20 +629,27 @@ def __call__(self, 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: @@ -562,6 +659,4 @@ 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 c024eb91195c..7db7c233ba6e 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,18 +14,15 @@ # 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.cloud.vision_v1p2beta1.types import image_annotator from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport class _BaseImageAnnotatorRestTransport(ImageAnnotatorTransport): @@ -41,14 +38,16 @@ 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,7 +71,9 @@ def __init__(self, *, # 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() @@ -83,27 +84,31 @@ def __init__(self, *, 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 @@ -118,17 +123,23 @@ 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 @@ -137,20 +148,24 @@ 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 @@ -165,22 +180,26 @@ 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 fbde77c956b4..3905e34e3f6b 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 @@ -46,6 +46,7 @@ ImageSource, InputConfig, LatLongRect, + Likelihood, LocationInfo, OperationMetadata, OutputConfig, @@ -53,7 +54,6 @@ SafeSearchAnnotation, TextDetectionParams, WebDetectionParams, - Likelihood, ) from .text_annotation import ( Block, @@ -68,49 +68,49 @@ ) __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 3ebc43555d87..269b5d8bc68c 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,14 +19,13 @@ 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", }, ) @@ -85,15 +84,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 970c22c8751c..d4636a74a300 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 @@ -19,52 +19,52 @@ 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 geometry, 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 - +from google.type import ( + color_pb2, # type: ignore + latlng_pb2, # type: ignore +) __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", }, ) @@ -92,6 +92,7 @@ class Likelihood(proto.Enum): It is very likely that the image belongs to the specified vertical. """ + UNKNOWN = 0 VERY_UNLIKELY = 1 UNLIKELY = 2 @@ -119,6 +120,7 @@ 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. @@ -153,6 +155,7 @@ class Type(proto.Enum): WEB_DETECTION (10): Run web detection. """ + TYPE_UNSPECIFIED = 0 FACE_DETECTION = 1 LANDMARK_DETECTION = 2 @@ -244,10 +247,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", ) @@ -317,6 +320,7 @@ 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 @@ -396,6 +400,7 @@ class Type(proto.Enum): CHIN_RIGHT_GONION (34): Chin right gonion. """ + UNKNOWN_LANDMARK = 0 LEFT_EYE = 1 RIGHT_EYE = 2 @@ -432,10 +437,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 +483,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 +635,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 +676,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 +763,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 +779,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 +826,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 +919,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 +959,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 +1045,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 +1100,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 +1121,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 +1143,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 +1159,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 +1182,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 +1213,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 +1230,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 +1247,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 +1267,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 +1299,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, @@ -1365,6 +1370,7 @@ class OperationMetadata(proto.Message): The time when the operation result was last updated. """ + class State(proto.Enum): r"""Batch operation states. @@ -1380,6 +1386,7 @@ class State(proto.Enum): CANCELLED (4): The batch processing was cancelled. """ + STATE_UNSPECIFIED = 0 CREATED = 1 RUNNING = 2 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 fef53f89cb80..b9d25b950022 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,16 +21,15 @@ 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", }, ) @@ -82,6 +81,7 @@ 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. @@ -101,6 +101,7 @@ class BreakType(proto.Enum): LINE_BREAK (5): Line break that ends a paragraph. """ + UNKNOWN = 0 SPACE = 1 SURE_SPACE = 2 @@ -108,10 +109,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,21 +130,23 @@ class TextProperty(proto.Message): Detected start or end of a text segment. """ - detected_languages: MutableSequence['TextAnnotation.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TextAnnotation.DetectedLanguage', + detected_languages: MutableSequence["TextAnnotation.DetectedLanguage"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + 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 +173,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 +186,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, @@ -235,6 +238,7 @@ 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. @@ -252,6 +256,7 @@ class BlockType(proto.Enum): BARCODE (5): Barcode block. """ + UNKNOWN = 0 TEXT = 1 TABLE = 2 @@ -259,20 +264,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, @@ -312,20 +317,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, @@ -359,20 +364,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, @@ -406,10 +411,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 557f1e2b4225..5b82e384e648 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,11 +19,10 @@ import proto # type: ignore - __protobuf__ = proto.module( - package='google.cloud.vision.v1p2beta1', + package="google.cloud.vision.v1p2beta1", manifest={ - 'WebDetection', + "WebDetection", }, ) @@ -136,15 +135,19 @@ class WebPage(proto.Message): proto.STRING, number=3, ) - full_matching_images: MutableSequence['WebDetection.WebImage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='WebDetection.WebImage', + full_matching_images: MutableSequence["WebDetection.WebImage"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=4, + message="WebDetection.WebImage", + ) ) - partial_matching_images: MutableSequence['WebDetection.WebImage'] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='WebDetection.WebImage', + partial_matching_images: MutableSequence["WebDetection.WebImage"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=5, + 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 6e317eaf354f..c9c687b9dccd 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from google.cloud.vision_v1p3beta1 import gapic_version as package_version +import sys import google.api_core as api_core -import sys +from google.cloud.vision_v1p3beta1 import gapic_version as package_version __version__ = package_version.__version__ @@ -28,116 +28,114 @@ import importlib_metadata as metadata -from .services.image_annotator import ImageAnnotatorClient -from .services.image_annotator import ImageAnnotatorAsyncClient -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 .services.image_annotator import ImageAnnotatorAsyncClient, ImageAnnotatorClient +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 .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 warnings import sys + import warnings _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. @@ -175,106 +173,110 @@ 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/") + 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 b1663fdd632d..c7f40549e472 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 .client import ImageAnnotatorClient from .async_client import ImageAnnotatorAsyncClient +from .client import ImageAnnotatorClient __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 2dd38756cf68..90d2740bb195 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 @@ -14,41 +14,55 @@ # limitations under the License. # import logging as std_logging -from collections import OrderedDict import re -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 collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) -from google.api_core.client_options import ClientOptions +import google.protobuf 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.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.vision_v1p3beta1 import gapic_version as package_version +from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore +from google.api_core import ( + operation, # type: ignore + operation_async, # type: ignore +) from google.cloud.vision_v1p3beta1.types import image_annotator -from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport + from .client import ImageAnnotatorClient +from .transports.base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport 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 @@ -69,16 +83,30 @@ 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): @@ -93,7 +121,9 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ImageAnnotatorAsyncClient: The constructed client. """ - return ImageAnnotatorClient.from_service_account_info.__func__(ImageAnnotatorAsyncClient, info, *args, **kwargs) # type: ignore + return ImageAnnotatorClient.from_service_account_info.__func__( + ImageAnnotatorAsyncClient, info, *args, **kwargs + ) # type: ignore @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -109,12 +139,16 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ImageAnnotatorAsyncClient: The constructed client. """ - return ImageAnnotatorClient.from_service_account_file.__func__(ImageAnnotatorAsyncClient, filename, *args, **kwargs) # type: ignore + return ImageAnnotatorClient.from_service_account_file.__func__( + ImageAnnotatorAsyncClient, filename, *args, **kwargs + ) # type: ignore 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: @@ -177,12 +211,16 @@ 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: @@ -237,31 +275,43 @@ def __init__(self, *, 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. @@ -319,10 +369,14 @@ 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. @@ -336,7 +390,9 @@ 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() @@ -352,14 +408,19 @@ 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 @@ -430,10 +491,14 @@ 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. @@ -447,7 +512,9 @@ 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() @@ -477,12 +544,13 @@ 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__) -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +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__ = ( - "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 09ec9b6596c7..ce9fae8f7992 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 @@ -13,27 +13,38 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict -from http import HTTPStatus import json import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) -from google.cloud.vision_v1p3beta1 import gapic_version as package_version - +import google.protobuf 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.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.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.cloud.vision_v1p3beta1 import gapic_version as package_version +from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -42,16 +53,20 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore +from google.api_core import ( + operation, # type: ignore + operation_async, # type: ignore +) from google.cloud.vision_v1p3beta1.types import image_annotator -from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO + +from .transports.base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport from .transports.grpc import ImageAnnotatorGrpcTransport from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport from .transports.rest import ImageAnnotatorRestTransport @@ -64,14 +79,16 @@ class ImageAnnotatorClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _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: @@ -147,14 +164,16 @@ 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" @@ -193,8 +212,7 @@ 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) @@ -211,84 +229,132 @@ 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: @@ -320,14 +386,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio 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 @@ -340,7 +410,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # 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 @@ -365,7 +437,9 @@ 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 @@ -388,7 +462,9 @@ 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: @@ -404,17 +480,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ 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: @@ -450,15 +534,18 @@ 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 @@ -491,12 +578,16 @@ 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: @@ -551,14 +642,22 @@ def __init__(self, *, 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 @@ -569,7 +668,9 @@ def __init__(self, *, 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 @@ -578,30 +679,40 @@ def __init__(self, *, 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 " - "directly." + "When providing a transport instance, provide its scopes directly." ) 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) @@ -620,28 +731,41 @@ def __init__(self, *, ) 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. @@ -699,10 +823,14 @@ 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. @@ -731,14 +859,19 @@ 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 @@ -809,10 +942,14 @@ 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. @@ -825,7 +962,9 @@ 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() @@ -863,16 +1002,11 @@ 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 d3a583db5759..1de28b3fb87a 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,20 +19,18 @@ from .base import ImageAnnotatorTransport from .grpc import ImageAnnotatorGrpcTransport from .grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport -from .rest import ImageAnnotatorRestTransport -from .rest import ImageAnnotatorRestInterceptor - +from .rest import ImageAnnotatorRestInterceptor, ImageAnnotatorRestTransport # 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 faa2ee4f3cac..7019358b6e55 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,21 @@ 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 +import google.auth # type: ignore +import google.protobuf from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, operations_v1 from google.api_core import retry as retries -from google.api_core import operations_v1 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 from google.cloud.vision_v1p3beta1.types import image_annotator -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # 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,24 +40,25 @@ 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: @@ -93,31 +93,43 @@ 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=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + 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=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + 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 @@ -148,21 +160,20 @@ 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() @@ -172,21 +183,24 @@ 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 @@ -194,6 +208,4 @@ 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 4f82d23bf360..cd2e279de727 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 @@ -19,24 +19,23 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union -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.protobuf.json_format import MessageToJson -import google.protobuf.message - import grpc # type: ignore import proto # type: ignore +import google.auth # type: ignore +import google.protobuf.message +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore from google.cloud.vision_v1p3beta1.types import image_annotator -from google.longrunning import operations_pb2 # type: ignore -from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport 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,7 +45,9 @@ 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 +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.ImageAnnotator", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -78,7 +79,11 @@ 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) @@ -93,7 +98,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, @@ -118,23 +123,26 @@ 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: @@ -258,19 +266,23 @@ def __init__(self, *, ) 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. @@ -306,13 +318,12 @@ def create_channel(cls, 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 @@ -332,9 +343,12 @@ 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 @@ -350,18 +364,20 @@ def batch_annotate_images(self) -> Callable[ # 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 @@ -382,13 +398,15 @@ def async_batch_annotate_files(self) -> Callable[ # 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', - request_serializer=image_annotator.AsyncBatchAnnotateFilesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, + 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() @@ -398,6 +416,4 @@ 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 2f72327db4b3..9a2e2c8a7d0c 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,32 +15,31 @@ # import inspect import json -import pickle import logging as std_logging +import pickle 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 +import grpc # type: ignore +import proto # type: ignore +from grpc.experimental import aio # type: ignore + +import google.protobuf.message 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.api_core import operations_v1 -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.cloud.vision_v1p3beta1.types import image_annotator +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 grpc.experimental import aio # type: ignore -from google.cloud.vision_v1p3beta1.types import image_annotator -from google.longrunning import operations_pb2 # type: ignore -from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO +from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport 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 @@ -48,9 +47,13 @@ _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): @@ -71,7 +74,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, @@ -82,7 +85,11 @@ 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) @@ -97,7 +104,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, @@ -127,13 +134,15 @@ 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. @@ -164,24 +173,26 @@ def create_channel(cls, 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: @@ -307,7 +318,9 @@ def __init__(self, *, 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) @@ -338,9 +351,12 @@ 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 @@ -356,18 +372,21 @@ def batch_annotate_images(self) -> Callable[ # 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 @@ -388,16 +407,18 @@ def async_batch_annotate_files(self) -> Callable[ # 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', - request_serializer=image_annotator.AsyncBatchAnnotateFilesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, + 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, @@ -420,8 +441,7 @@ 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, @@ -442,6 +462,4 @@ 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 d6e3efadf1cb..110f3c387a2f 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,33 +13,26 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import logging -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 retry as retries -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 json # type: ignore +import logging import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +from requests import __version__ as requests_version +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_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.cloud.vision_v1p3beta1.types import image_annotator from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format - -from .rest_base import _BaseImageAnnotatorRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseImageAnnotatorRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -48,6 +41,7 @@ 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 @@ -100,7 +94,15 @@ 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 @@ -108,7 +110,9 @@ def pre_async_batch_annotate_files(self, request: image_annotator.AsyncBatchAnno """ 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` @@ -121,7 +125,11 @@ def post_async_batch_annotate_files(self, response: operations_pb2.Operation) -> """ 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 @@ -136,7 +144,14 @@ def post_async_batch_annotate_files_with_metadata(self, response: operations_pb2 """ 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 @@ -144,7 +159,9 @@ def pre_batch_annotate_images(self, request: image_annotator.BatchAnnotateImages """ 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` @@ -157,7 +174,14 @@ def post_batch_annotate_images(self, response: image_annotator.BatchAnnotateImag """ 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 @@ -195,20 +219,21 @@ 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: @@ -252,10 +277,11 @@ def __init__(self, *, 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) @@ -271,23 +297,28 @@ 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") @@ -299,77 +330,91 @@ 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() - 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, @@ -378,7 +423,17 @@ def __call__(self, ) # 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. @@ -391,20 +446,24 @@ def __call__(self, 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"], @@ -413,7 +472,10 @@ def __call__(self, ) return resp - class _BatchAnnotateImages(_BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages, ImageAnnotatorRestStub): + class _BatchAnnotateImages( + _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages, + ImageAnnotatorRestStub, + ): def __hash__(self): return hash("ImageAnnotatorRestTransport.BatchAnnotateImages") @@ -425,27 +487,29 @@ 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: @@ -469,30 +533,42 @@ def __call__(self, 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, @@ -501,7 +577,15 @@ def __call__(self, ) # 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. @@ -516,20 +600,26 @@ def __call__(self, 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"], @@ -539,20 +629,27 @@ def __call__(self, 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: @@ -562,6 +659,4 @@ 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 f8a9283b73cf..e186e4b91f96 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,18 +14,15 @@ # 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.cloud.vision_v1p3beta1.types import image_annotator from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport class _BaseImageAnnotatorRestTransport(ImageAnnotatorTransport): @@ -41,14 +38,16 @@ 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,7 +71,9 @@ def __init__(self, *, # 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() @@ -83,27 +84,31 @@ def __init__(self, *, 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 @@ -118,17 +123,23 @@ 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 @@ -137,20 +148,24 @@ 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 @@ -165,22 +180,26 @@ 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 ff3cc167408d..f2e4fe58e8df 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 .client import ProductSearchClient from .async_client import ProductSearchAsyncClient +from .client import ProductSearchClient __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 bffd9c75d701..43b5ad311964 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 @@ -14,46 +14,61 @@ # limitations under the License. # import logging as std_logging -from collections import OrderedDict import re -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 collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) -from google.api_core.client_options import ClientOptions +import google.protobuf 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.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.vision_v1p3beta1 import gapic_version as package_version +from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore +from google.api_core import ( + operation, # type: ignore + 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.cloud.vision_v1p3beta1.types import geometry, product_search_service +from google.protobuf import ( + field_mask_pb2, # type: ignore + timestamp_pb2, # type: ignore +) from google.rpc import status_pb2 # type: ignore -from .transports.base import ProductSearchTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ProductSearchGrpcAsyncIOTransport + from .client import ProductSearchClient +from .transports.base import DEFAULT_CLIENT_INFO, ProductSearchTransport +from .transports.grpc_asyncio import ProductSearchGrpcAsyncIOTransport 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: @@ -91,17 +106,33 @@ 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): @@ -116,7 +147,9 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ProductSearchAsyncClient: The constructed client. """ - return ProductSearchClient.from_service_account_info.__func__(ProductSearchAsyncClient, info, *args, **kwargs) # type: ignore + return ProductSearchClient.from_service_account_info.__func__( + ProductSearchAsyncClient, info, *args, **kwargs + ) # type: ignore @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -132,12 +165,16 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ProductSearchAsyncClient: The constructed client. """ - return ProductSearchClient.from_service_account_file.__func__(ProductSearchAsyncClient, filename, *args, **kwargs) # type: ignore + return ProductSearchClient.from_service_account_file.__func__( + ProductSearchAsyncClient, filename, *args, **kwargs + ) # type: ignore 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,12 +237,16 @@ 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: @@ -260,33 +301,43 @@ def __init__(self, *, 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: @@ -368,10 +419,14 @@ 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. @@ -389,14 +444,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. @@ -413,14 +468,17 @@ 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: @@ -487,10 +545,14 @@ 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. @@ -504,14 +566,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. @@ -539,14 +601,17 @@ 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: @@ -612,10 +677,14 @@ 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. @@ -629,14 +698,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. @@ -653,15 +722,18 @@ 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. @@ -737,10 +809,14 @@ 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. @@ -756,14 +832,16 @@ 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. @@ -780,14 +858,17 @@ 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. @@ -845,10 +926,14 @@ 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. @@ -862,14 +947,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. @@ -883,16 +968,19 @@ 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: @@ -973,10 +1061,14 @@ 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. @@ -994,14 +1086,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. @@ -1018,14 +1110,17 @@ 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: @@ -1092,10 +1187,14 @@ 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. @@ -1109,14 +1208,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. @@ -1144,14 +1243,15 @@ 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: @@ -1212,10 +1312,14 @@ 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. @@ -1229,14 +1333,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. @@ -1253,15 +1357,18 @@ 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. @@ -1341,10 +1448,14 @@ 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. @@ -1360,14 +1471,16 @@ 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. @@ -1384,14 +1497,17 @@ 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 @@ -1449,10 +1565,14 @@ 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. @@ -1466,14 +1586,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. @@ -1487,16 +1607,19 @@ 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 @@ -1599,10 +1722,14 @@ 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. @@ -1620,14 +1747,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. @@ -1644,14 +1771,17 @@ 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 @@ -1714,10 +1844,14 @@ 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. @@ -1731,14 +1865,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. @@ -1752,14 +1886,17 @@ 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: @@ -1828,10 +1965,14 @@ 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. @@ -1845,14 +1986,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. @@ -1880,14 +2021,17 @@ 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: @@ -1952,10 +2096,14 @@ 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. @@ -1969,14 +2117,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. @@ -1993,15 +2141,18 @@ 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. @@ -2072,14 +2223,20 @@ 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 @@ -2091,14 +2248,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. @@ -2112,15 +2269,18 @@ 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: @@ -2188,14 +2348,20 @@ 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 @@ -2207,14 +2373,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. @@ -2228,14 +2394,17 @@ 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. @@ -2307,14 +2476,20 @@ 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 @@ -2324,14 +2499,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. @@ -2359,15 +2534,20 @@ 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. @@ -2457,10 +2637,14 @@ 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. @@ -2476,14 +2660,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. @@ -2514,12 +2698,13 @@ 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__) -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +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__ = ( - "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 77f866ee7821..1bc7f8efcfdf 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 @@ -13,27 +13,38 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict -from http import HTTPStatus import json import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) -from google.cloud.vision_v1p3beta1 import gapic_version as package_version - +import google.protobuf 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.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.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.cloud.vision_v1p3beta1 import gapic_version as package_version +from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -42,21 +53,26 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore +from google.api_core import ( + operation, # type: ignore + 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.cloud.vision_v1p3beta1.types import geometry, product_search_service +from google.protobuf import ( + field_mask_pb2, # type: ignore + timestamp_pb2, # type: ignore +) from google.rpc import status_pb2 # type: ignore -from .transports.base import ProductSearchTransport, DEFAULT_CLIENT_INFO + +from .transports.base import DEFAULT_CLIENT_INFO, ProductSearchTransport from .transports.grpc import ProductSearchGrpcTransport from .transports.grpc_asyncio import ProductSearchGrpcAsyncIOTransport from .transports.rest import ProductSearchRestTransport @@ -69,14 +85,16 @@ 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: @@ -168,14 +186,16 @@ 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,8 +234,7 @@ 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) @@ -232,95 +251,156 @@ 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: @@ -352,14 +432,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio 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 @@ -372,7 +456,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # 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 @@ -397,7 +483,9 @@ 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 @@ -420,7 +508,9 @@ 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: @@ -436,17 +526,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ 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: @@ -482,15 +580,18 @@ 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 @@ -523,12 +624,16 @@ 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: @@ -583,14 +688,22 @@ def __init__(self, *, 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 @@ -601,7 +714,9 @@ def __init__(self, *, 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 @@ -610,30 +725,40 @@ def __init__(self, *, 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 " - "directly." + "When providing a transport instance, provide its scopes directly." ) 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) @@ -652,30 +777,41 @@ def __init__(self, *, ) 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: @@ -757,10 +893,14 @@ 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. @@ -782,9 +922,7 @@ 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. @@ -801,14 +939,17 @@ 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: @@ -875,10 +1016,14 @@ 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. @@ -896,9 +1041,7 @@ 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. @@ -926,14 +1069,17 @@ 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: @@ -999,10 +1145,14 @@ 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. @@ -1020,9 +1170,7 @@ 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. @@ -1039,15 +1187,18 @@ 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. @@ -1123,10 +1274,14 @@ 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. @@ -1146,9 +1301,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. @@ -1165,14 +1320,17 @@ 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. @@ -1230,10 +1388,14 @@ 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. @@ -1251,9 +1413,7 @@ 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. @@ -1267,16 +1427,19 @@ 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: @@ -1357,10 +1520,14 @@ 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. @@ -1382,9 +1549,7 @@ 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. @@ -1401,14 +1566,17 @@ 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: @@ -1475,10 +1643,14 @@ 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. @@ -1496,9 +1668,7 @@ 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. @@ -1526,14 +1696,15 @@ 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: @@ -1594,10 +1765,14 @@ 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. @@ -1615,9 +1790,7 @@ 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. @@ -1634,15 +1807,18 @@ 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. @@ -1722,10 +1898,14 @@ 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. @@ -1745,9 +1925,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. @@ -1764,14 +1944,17 @@ 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 @@ -1829,10 +2012,14 @@ 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. @@ -1850,9 +2037,7 @@ 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. @@ -1866,16 +2051,19 @@ 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 @@ -1978,10 +2166,14 @@ 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. @@ -2003,9 +2195,7 @@ 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. @@ -2022,14 +2212,17 @@ 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 @@ -2092,10 +2285,14 @@ 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. @@ -2113,9 +2310,7 @@ 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. @@ -2129,14 +2324,17 @@ 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: @@ -2205,10 +2403,14 @@ 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. @@ -2226,9 +2428,7 @@ 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. @@ -2256,14 +2456,17 @@ 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: @@ -2328,10 +2531,14 @@ 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. @@ -2349,9 +2556,7 @@ 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. @@ -2368,15 +2573,18 @@ 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. @@ -2447,14 +2655,20 @@ 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. @@ -2465,14 +2679,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. @@ -2486,15 +2700,18 @@ 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: @@ -2562,14 +2779,20 @@ 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. @@ -2580,14 +2803,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. @@ -2601,14 +2824,17 @@ 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. @@ -2680,14 +2906,20 @@ 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. @@ -2696,14 +2928,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. @@ -2731,15 +2963,20 @@ 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. @@ -2829,10 +3066,14 @@ 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. @@ -2852,9 +3093,7 @@ 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. @@ -2893,16 +3132,11 @@ 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 5c6237435803..9913867a51ff 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,13 +13,27 @@ # 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 @@ -44,14 +58,17 @@ 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: @@ -84,7 +101,12 @@ 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]: @@ -92,7 +114,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: @@ -112,14 +134,19 @@ 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: @@ -148,12 +175,20 @@ 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: @@ -163,7 +198,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: @@ -183,14 +218,17 @@ 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: @@ -223,7 +261,12 @@ 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]: @@ -231,7 +274,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: @@ -251,14 +294,17 @@ 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: @@ -291,8 +337,14 @@ 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: @@ -302,7 +354,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: @@ -322,14 +374,17 @@ 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: @@ -362,7 +417,12 @@ 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]: @@ -370,7 +430,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: @@ -390,14 +450,19 @@ 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: @@ -426,12 +491,20 @@ 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: @@ -441,7 +514,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: @@ -461,14 +534,17 @@ 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: @@ -497,11 +573,18 @@ 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]: @@ -509,7 +592,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: @@ -529,14 +612,19 @@ 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: @@ -565,12 +653,20 @@ 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: @@ -580,4 +676,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 f5f6aac78c26..e3bd7adc48d8 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,20 +19,18 @@ from .base import ProductSearchTransport from .grpc import ProductSearchGrpcTransport from .grpc_asyncio import ProductSearchGrpcAsyncIOTransport -from .rest import ProductSearchRestTransport -from .rest import ProductSearchRestInterceptor - +from .rest import ProductSearchRestInterceptor, ProductSearchRestTransport # 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 fdb031d4ef7f..d14337a52fe4 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,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 +import google.auth # type: ignore +import google.protobuf from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, operations_v1 from google.api_core import retry as retries -from google.api_core import operations_v1 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 from google.cloud.vision_v1p3beta1.types import product_search_service -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # 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,24 +41,25 @@ 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: @@ -94,31 +94,43 @@ 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=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + 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=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + 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 @@ -134,8 +146,7 @@ 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, @@ -177,8 +188,7 @@ 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, @@ -205,8 +215,7 @@ 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, @@ -248,8 +257,7 @@ 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, @@ -276,8 +284,7 @@ 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, @@ -334,8 +341,7 @@ 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, @@ -347,8 +353,7 @@ 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, @@ -375,21 +380,20 @@ 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() @@ -399,165 +403,198 @@ 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 @@ -565,6 +602,4 @@ 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 277ad601a4cb..fe5991cb78b3 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 @@ -19,25 +19,24 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union -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.protobuf.json_format import MessageToJson -import google.protobuf.message - import grpc # type: ignore import proto # type: ignore +import google.auth # type: ignore +import google.protobuf.message +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore from google.cloud.vision_v1p3beta1.types import product_search_service -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore -from .base import ProductSearchTransport, DEFAULT_CLIENT_INFO +from google.protobuf.json_format import MessageToJson + +from .base import DEFAULT_CLIENT_INFO, ProductSearchTransport 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,7 +46,9 @@ 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 +69,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, @@ -79,7 +80,11 @@ 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) @@ -94,7 +99,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, @@ -135,23 +140,26 @@ 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: @@ -275,19 +283,23 @@ def __init__(self, *, ) 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. @@ -323,13 +335,12 @@ def create_channel(cls, 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 @@ -349,9 +360,12 @@ 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. @@ -371,18 +385,21 @@ def create_product_set(self) -> Callable[ # 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. @@ -402,18 +419,20 @@ def list_product_sets(self) -> Callable[ # 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. @@ -432,18 +451,21 @@ def get_product_set(self) -> Callable[ # 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 @@ -466,18 +488,18 @@ def update_product_set(self) -> Callable[ # 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 @@ -500,18 +522,20 @@ def delete_product_set(self) -> Callable[ # 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. @@ -535,18 +559,21 @@ def create_product(self) -> Callable[ # 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. @@ -566,18 +593,20 @@ def list_products(self) -> Callable[ # 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. @@ -596,18 +625,20 @@ def get_product(self) -> Callable[ # 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, @@ -637,18 +668,18 @@ def update_product(self) -> Callable[ # 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. @@ -671,18 +702,21 @@ def delete_product(self) -> Callable[ # 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. @@ -718,18 +752,20 @@ def create_reference_image(self) -> Callable[ # 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. @@ -755,18 +791,21 @@ def delete_reference_image(self) -> Callable[ # 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. @@ -787,18 +826,21 @@ def list_reference_images(self) -> Callable[ # 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. @@ -817,18 +859,20 @@ def get_reference_image(self) -> Callable[ # 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 @@ -851,18 +895,22 @@ def add_product_to_product_set(self) -> Callable[ # 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', - request_serializer=product_search_service.AddProductToProductSetRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, + 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. @@ -883,18 +931,23 @@ def remove_product_from_product_set(self) -> Callable[ # 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', - request_serializer=product_search_service.RemoveProductFromProductSetRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, + 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 @@ -916,18 +969,22 @@ def list_products_in_product_set(self) -> Callable[ # 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', - request_serializer=product_search_service.ListProductsInProductSetRequest.serialize, - response_deserializer=product_search_service.ListProductsInProductSetResponse.deserialize, + 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 @@ -953,13 +1010,13 @@ def import_product_sets(self) -> Callable[ # 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() @@ -969,6 +1026,4 @@ 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 4a46b4662d45..bec18a4fc85f 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,33 +15,32 @@ # import inspect import json -import pickle import logging as std_logging +import pickle 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 +import grpc # type: ignore +import proto # type: ignore +from grpc.experimental import aio # type: ignore + +import google.protobuf.message 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.api_core import operations_v1 -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 proto # type: ignore -from grpc.experimental import aio # type: ignore - from google.cloud.vision_v1p3beta1.types import product_search_service -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore -from .base import ProductSearchTransport, DEFAULT_CLIENT_INFO +from google.protobuf.json_format import MessageToJson + +from .base import DEFAULT_CLIENT_INFO, ProductSearchTransport 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 @@ -49,9 +48,13 @@ _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): @@ -72,7 +75,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, @@ -83,7 +86,11 @@ 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) @@ -98,7 +105,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, @@ -144,13 +151,15 @@ 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. @@ -181,24 +190,26 @@ def create_channel(cls, 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: @@ -324,7 +335,9 @@ def __init__(self, *, 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) @@ -355,9 +368,12 @@ 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. @@ -377,18 +393,21 @@ def create_product_set(self) -> Callable[ # 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. @@ -408,18 +427,21 @@ def list_product_sets(self) -> Callable[ # 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. @@ -438,18 +460,21 @@ def get_product_set(self) -> Callable[ # 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 @@ -472,18 +497,20 @@ def update_product_set(self) -> Callable[ # 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 @@ -506,18 +533,21 @@ def delete_product_set(self) -> Callable[ # 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. @@ -541,18 +571,21 @@ def create_product(self) -> Callable[ # 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. @@ -572,18 +605,21 @@ def list_products(self) -> Callable[ # 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. @@ -602,18 +638,21 @@ def get_product(self) -> Callable[ # 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, @@ -643,18 +682,20 @@ def update_product(self) -> Callable[ # 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. @@ -677,18 +718,21 @@ def delete_product(self) -> Callable[ # 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. @@ -724,18 +768,20 @@ def create_reference_image(self) -> Callable[ # 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. @@ -761,18 +807,21 @@ def delete_reference_image(self) -> Callable[ # 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. @@ -793,18 +842,21 @@ def list_reference_images(self) -> Callable[ # 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. @@ -823,18 +875,21 @@ def get_reference_image(self) -> Callable[ # 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 @@ -857,18 +912,23 @@ def add_product_to_product_set(self) -> Callable[ # 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', - request_serializer=product_search_service.AddProductToProductSetRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, + 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. @@ -889,18 +949,23 @@ def remove_product_from_product_set(self) -> Callable[ # 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', - request_serializer=product_search_service.RemoveProductFromProductSetRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, + 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 @@ -922,18 +987,23 @@ def list_products_in_product_set(self) -> Callable[ # 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', - request_serializer=product_search_service.ListProductsInProductSetRequest.serialize, - response_deserializer=product_search_service.ListProductsInProductSetResponse.deserialize, + 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 @@ -959,16 +1029,16 @@ def import_product_sets(self) -> Callable[ # 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, @@ -976,8 +1046,7 @@ 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, @@ -1019,8 +1088,7 @@ 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, @@ -1047,8 +1115,7 @@ 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, @@ -1090,8 +1157,7 @@ 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, @@ -1118,8 +1184,7 @@ 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, @@ -1176,8 +1241,7 @@ 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, @@ -1189,8 +1253,7 @@ 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, @@ -1217,8 +1280,7 @@ 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, @@ -1239,6 +1301,4 @@ 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 bdd00830e0d4..058c73a504f0 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,34 +13,29 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import logging -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 retry as retries -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 json # type: ignore +import logging import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +from requests import __version__ as requests_version +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_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.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 google.protobuf import ( + empty_pb2, # type: ignore + json_format, +) - -from .rest_base import _BaseProductSearchRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseProductSearchRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -49,6 +44,7 @@ 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 @@ -209,7 +205,15 @@ 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 @@ -217,7 +221,14 @@ def pre_add_product_to_product_set(self, request: product_search_service.AddProd """ 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 @@ -225,7 +236,9 @@ def pre_create_product(self, request: product_search_service.CreateProductReques """ 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` @@ -238,7 +251,11 @@ def post_create_product(self, response: product_search_service.Product) -> produ """ 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 @@ -253,7 +270,14 @@ def post_create_product_with_metadata(self, response: product_search_service.Pro """ 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 @@ -261,7 +285,9 @@ def pre_create_product_set(self, request: product_search_service.CreateProductSe """ 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` @@ -274,7 +300,13 @@ def post_create_product_set(self, response: product_search_service.ProductSet) - """ 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 @@ -289,7 +321,14 @@ def post_create_product_set_with_metadata(self, response: product_search_service """ 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 @@ -297,7 +336,9 @@ def pre_create_reference_image(self, request: product_search_service.CreateRefer """ 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` @@ -310,7 +351,13 @@ def post_create_reference_image(self, response: product_search_service.Reference """ 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 @@ -325,7 +372,14 @@ def post_create_reference_image_with_metadata(self, response: product_search_ser """ 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 @@ -333,7 +387,14 @@ def pre_delete_product(self, request: product_search_service.DeleteProductReques """ 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 @@ -341,7 +402,14 @@ def pre_delete_product_set(self, request: product_search_service.DeleteProductSe """ 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 @@ -349,7 +417,14 @@ def pre_delete_reference_image(self, request: product_search_service.DeleteRefer """ 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 @@ -357,7 +432,9 @@ def pre_get_product(self, request: product_search_service.GetProductRequest, met """ 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` @@ -370,7 +447,11 @@ def post_get_product(self, response: product_search_service.Product) -> 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 @@ -385,7 +466,14 @@ def post_get_product_with_metadata(self, response: product_search_service.Produc """ 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 @@ -393,7 +481,9 @@ def pre_get_product_set(self, request: product_search_service.GetProductSetReque """ 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` @@ -406,7 +496,13 @@ def post_get_product_set(self, response: product_search_service.ProductSet) -> p """ 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 @@ -421,7 +517,14 @@ def post_get_product_set_with_metadata(self, response: product_search_service.Pr """ 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 @@ -429,7 +532,9 @@ def pre_get_reference_image(self, request: product_search_service.GetReferenceIm """ 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` @@ -442,7 +547,13 @@ def post_get_reference_image(self, response: product_search_service.ReferenceIma """ 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 @@ -457,7 +568,14 @@ def post_get_reference_image_with_metadata(self, response: product_search_servic """ 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 @@ -465,7 +583,9 @@ def pre_import_product_sets(self, request: product_search_service.ImportProductS """ 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` @@ -478,7 +598,11 @@ def post_import_product_sets(self, response: operations_pb2.Operation) -> operat """ 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 @@ -493,7 +617,14 @@ def post_import_product_sets_with_metadata(self, response: operations_pb2.Operat """ 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 @@ -501,7 +632,9 @@ def pre_list_products(self, request: product_search_service.ListProductsRequest, """ 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` @@ -514,7 +647,14 @@ def post_list_products(self, response: product_search_service.ListProductsRespon """ 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 @@ -529,7 +669,14 @@ def post_list_products_with_metadata(self, response: product_search_service.List """ 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 @@ -537,7 +684,9 @@ def pre_list_product_sets(self, request: product_search_service.ListProductSetsR """ 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` @@ -550,7 +699,14 @@ def post_list_product_sets(self, response: product_search_service.ListProductSet """ 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 @@ -565,7 +721,14 @@ def post_list_product_sets_with_metadata(self, response: product_search_service. """ 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 @@ -573,7 +736,9 @@ def pre_list_products_in_product_set(self, request: product_search_service.ListP """ 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` @@ -586,7 +751,14 @@ def post_list_products_in_product_set(self, response: product_search_service.Lis """ 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 @@ -601,7 +773,14 @@ def post_list_products_in_product_set_with_metadata(self, response: product_sear """ 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 @@ -609,7 +788,9 @@ def pre_list_reference_images(self, request: product_search_service.ListReferenc """ 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` @@ -622,7 +803,14 @@ def post_list_reference_images(self, response: product_search_service.ListRefere """ 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 @@ -637,7 +825,14 @@ def post_list_reference_images_with_metadata(self, response: product_search_serv """ 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 @@ -645,7 +840,14 @@ def pre_remove_product_from_product_set(self, request: product_search_service.Re """ 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 @@ -653,7 +855,9 @@ def pre_update_product(self, request: product_search_service.UpdateProductReques """ 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` @@ -666,7 +870,11 @@ def post_update_product(self, response: product_search_service.Product) -> produ """ 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 @@ -681,7 +889,14 @@ def post_update_product_with_metadata(self, response: product_search_service.Pro """ 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 @@ -689,7 +904,9 @@ def pre_update_product_set(self, request: product_search_service.UpdateProductSe """ 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` @@ -702,7 +919,13 @@ def post_update_product_set(self, response: product_search_service.ProductSet) - """ 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 @@ -756,20 +979,21 @@ 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: @@ -813,10 +1037,11 @@ def __init__(self, *, 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) @@ -832,23 +1057,28 @@ 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") @@ -860,69 +1090,83 @@ 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() - 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, @@ -931,14 +1175,24 @@ def __call__(self, ) # 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") @@ -950,27 +1204,29 @@ 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: @@ -989,32 +1245,44 @@ def __call__(self, 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, @@ -1023,7 +1291,15 @@ def __call__(self, ) # 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. @@ -1038,20 +1314,24 @@ def __call__(self, 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"], @@ -1060,7 +1340,9 @@ def __call__(self, ) return resp - class _CreateProductSet(_BaseProductSearchRestTransport._BaseCreateProductSet, ProductSearchRestStub): + class _CreateProductSet( + _BaseProductSearchRestTransport._BaseCreateProductSet, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.CreateProductSet") @@ -1072,27 +1354,29 @@ 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: @@ -1118,30 +1402,42 @@ def __call__(self, 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, @@ -1150,7 +1446,15 @@ def __call__(self, ) # 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. @@ -1165,20 +1469,26 @@ def __call__(self, 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"], @@ -1187,7 +1497,9 @@ def __call__(self, ) return resp - class _CreateReferenceImage(_BaseProductSearchRestTransport._BaseCreateReferenceImage, ProductSearchRestStub): + class _CreateReferenceImage( + _BaseProductSearchRestTransport._BaseCreateReferenceImage, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.CreateReferenceImage") @@ -1199,27 +1511,29 @@ 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: @@ -1242,30 +1556,42 @@ def __call__(self, 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, @@ -1274,7 +1600,15 @@ def __call__(self, ) # 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. @@ -1289,20 +1623,26 @@ def __call__(self, 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"], @@ -1311,7 +1651,9 @@ def __call__(self, ) return resp - class _DeleteProduct(_BaseProductSearchRestTransport._BaseDeleteProduct, ProductSearchRestStub): + class _DeleteProduct( + _BaseProductSearchRestTransport._BaseDeleteProduct, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.DeleteProduct") @@ -1323,26 +1665,28 @@ 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: @@ -1357,30 +1701,40 @@ def __call__(self, 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, @@ -1389,14 +1743,23 @@ def __call__(self, ) # 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") @@ -1408,26 +1771,28 @@ 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: @@ -1444,28 +1809,38 @@ def __call__(self, 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, @@ -1474,14 +1849,23 @@ def __call__(self, ) # 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") @@ -1493,26 +1877,28 @@ 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: @@ -1529,28 +1915,38 @@ def __call__(self, 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, @@ -1559,14 +1955,23 @@ def __call__(self, ) # 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") @@ -1578,26 +1983,28 @@ 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: @@ -1616,30 +2023,44 @@ def __call__(self, 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, @@ -1648,7 +2069,14 @@ def __call__(self, ) # 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. @@ -1663,20 +2091,24 @@ def __call__(self, 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"], @@ -1685,7 +2117,9 @@ def __call__(self, ) return resp - class _GetProductSet(_BaseProductSearchRestTransport._BaseGetProductSet, ProductSearchRestStub): + class _GetProductSet( + _BaseProductSearchRestTransport._BaseGetProductSet, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.GetProductSet") @@ -1697,26 +2131,28 @@ 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: @@ -1740,30 +2176,40 @@ def __call__(self, """ - 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, @@ -1772,7 +2218,14 @@ def __call__(self, ) # 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. @@ -1787,20 +2240,26 @@ def __call__(self, 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"], @@ -1809,7 +2268,9 @@ def __call__(self, ) return resp - class _GetReferenceImage(_BaseProductSearchRestTransport._BaseGetReferenceImage, ProductSearchRestStub): + class _GetReferenceImage( + _BaseProductSearchRestTransport._BaseGetReferenceImage, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.GetReferenceImage") @@ -1821,26 +2282,28 @@ 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: @@ -1863,28 +2326,38 @@ def __call__(self, 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, @@ -1893,7 +2366,14 @@ def __call__(self, ) # 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. @@ -1908,20 +2388,26 @@ def __call__(self, 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"], @@ -1930,7 +2416,9 @@ def __call__(self, ) return resp - class _ImportProductSets(_BaseProductSearchRestTransport._BaseImportProductSets, ProductSearchRestStub): + class _ImportProductSets( + _BaseProductSearchRestTransport._BaseImportProductSets, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.ImportProductSets") @@ -1942,27 +2430,29 @@ 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: @@ -1986,30 +2476,42 @@ def __call__(self, 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, @@ -2018,7 +2520,15 @@ def __call__(self, ) # 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. @@ -2031,20 +2541,24 @@ def __call__(self, 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"], @@ -2053,7 +2567,9 @@ def __call__(self, ) return resp - class _ListProducts(_BaseProductSearchRestTransport._BaseListProducts, ProductSearchRestStub): + class _ListProducts( + _BaseProductSearchRestTransport._BaseListProducts, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.ListProducts") @@ -2065,26 +2581,28 @@ 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: @@ -2103,30 +2621,40 @@ def __call__(self, 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, @@ -2135,7 +2663,14 @@ def __call__(self, ) # 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. @@ -2150,20 +2685,26 @@ def __call__(self, 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"], @@ -2172,7 +2713,9 @@ def __call__(self, ) return resp - class _ListProductSets(_BaseProductSearchRestTransport._BaseListProductSets, ProductSearchRestStub): + class _ListProductSets( + _BaseProductSearchRestTransport._BaseListProductSets, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.ListProductSets") @@ -2184,26 +2727,28 @@ 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: @@ -2222,30 +2767,42 @@ def __call__(self, 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, @@ -2254,7 +2811,14 @@ def __call__(self, ) # 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. @@ -2269,20 +2833,26 @@ def __call__(self, 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"], @@ -2291,7 +2861,10 @@ def __call__(self, ) return resp - class _ListProductsInProductSet(_BaseProductSearchRestTransport._BaseListProductsInProductSet, ProductSearchRestStub): + class _ListProductsInProductSet( + _BaseProductSearchRestTransport._BaseListProductsInProductSet, + ProductSearchRestStub, + ): def __hash__(self): return hash("ProductSearchRestTransport.ListProductsInProductSet") @@ -2303,72 +2876,84 @@ 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() - 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, @@ -2377,7 +2962,16 @@ def __call__(self, ) # 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. @@ -2392,20 +2986,28 @@ def __call__(self, 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"], @@ -2414,7 +3016,9 @@ def __call__(self, ) return resp - class _ListReferenceImages(_BaseProductSearchRestTransport._BaseListReferenceImages, ProductSearchRestStub): + class _ListReferenceImages( + _BaseProductSearchRestTransport._BaseListReferenceImages, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.ListReferenceImages") @@ -2426,26 +3030,28 @@ 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: @@ -2466,28 +3072,38 @@ def __call__(self, 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, @@ -2496,7 +3112,14 @@ def __call__(self, ) # 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. @@ -2511,20 +3134,28 @@ def __call__(self, 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"], @@ -2533,7 +3164,10 @@ def __call__(self, ) return resp - class _RemoveProductFromProductSet(_BaseProductSearchRestTransport._BaseRemoveProductFromProductSet, ProductSearchRestStub): + class _RemoveProductFromProductSet( + _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet, + ProductSearchRestStub, + ): def __hash__(self): return hash("ProductSearchRestTransport.RemoveProductFromProductSet") @@ -2545,69 +3179,83 @@ 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() - 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, @@ -2616,14 +3264,26 @@ def __call__(self, ) # 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") @@ -2635,27 +3295,29 @@ 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: @@ -2674,32 +3336,44 @@ def __call__(self, 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, @@ -2708,7 +3382,15 @@ def __call__(self, ) # 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. @@ -2723,20 +3405,24 @@ def __call__(self, 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"], @@ -2745,7 +3431,9 @@ def __call__(self, ) return resp - class _UpdateProductSet(_BaseProductSearchRestTransport._BaseUpdateProductSet, ProductSearchRestStub): + class _UpdateProductSet( + _BaseProductSearchRestTransport._BaseUpdateProductSet, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.UpdateProductSet") @@ -2757,27 +3445,29 @@ 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: @@ -2803,30 +3493,42 @@ def __call__(self, 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, @@ -2835,7 +3537,15 @@ def __call__(self, ) # 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. @@ -2850,20 +3560,26 @@ def __call__(self, 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"], @@ -2873,148 +3589,194 @@ def __call__(self, 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: @@ -3024,6 +3786,4 @@ 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 9ebf408586b5..213f135f11e7 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,19 +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 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.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 google.protobuf import ( + empty_pb2, # type: ignore + json_format, +) + +from .base import DEFAULT_CLIENT_INFO, ProductSearchTransport class _BaseProductSearchRestTransport(ProductSearchTransport): @@ -42,14 +41,16 @@ 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,7 +74,9 @@ def __init__(self, *, # 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,33 +87,39 @@ def __init__(self, *, 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 @@ -119,17 +128,23 @@ 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 @@ -138,20 +153,24 @@ 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 @@ -166,17 +185,23 @@ 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 @@ -185,20 +210,24 @@ 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 @@ -213,17 +242,23 @@ 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 @@ -232,20 +267,24 @@ 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 @@ -260,17 +299,23 @@ 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 @@ -279,19 +324,23 @@ 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 @@ -303,11 +352,17 @@ 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 @@ -316,19 +371,23 @@ 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 @@ -340,11 +399,17 @@ 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 @@ -353,19 +418,23 @@ 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 @@ -377,11 +446,17 @@ 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 @@ -390,19 +465,23 @@ 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 @@ -414,11 +493,17 @@ 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 @@ -427,19 +512,23 @@ 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 @@ -451,11 +540,17 @@ 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 @@ -464,19 +559,23 @@ 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 @@ -488,11 +587,17 @@ 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 @@ -501,20 +606,24 @@ 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 @@ -529,17 +638,23 @@ 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 @@ -548,19 +663,23 @@ 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 @@ -572,11 +691,17 @@ 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 @@ -585,19 +710,23 @@ 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 @@ -609,11 +738,17 @@ 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 @@ -622,35 +757,47 @@ 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 @@ -659,19 +806,23 @@ 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 @@ -683,11 +834,17 @@ 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 @@ -696,26 +853,32 @@ 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 @@ -724,17 +887,23 @@ 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 @@ -743,20 +912,24 @@ 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 @@ -771,17 +944,23 @@ 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 @@ -790,20 +969,24 @@ 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 @@ -818,22 +1001,26 @@ 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 652b20e0e18c..0c838e6d7f41 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 @@ -46,6 +46,7 @@ ImageSource, InputConfig, LatLongRect, + Likelihood, LocalizedObjectAnnotation, LocationInfo, OperationMetadata, @@ -54,7 +55,6 @@ SafeSearchAnnotation, TextDetectionParams, WebDetectionParams, - Likelihood, ) from .product_search import ( ProductSearchParams, @@ -104,81 +104,81 @@ ) __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 d7e647bb32d1..d885e4d5e3c2 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,14 +19,13 @@ 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", }, ) @@ -85,15 +84,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 71eb551fe9f9..6d3f2dece1ed 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 @@ -19,54 +19,57 @@ 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 ( + geometry, + product_search, + 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 - +from google.type import ( + color_pb2, # type: ignore + latlng_pb2, # type: ignore +) __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", }, ) @@ -94,6 +97,7 @@ class Likelihood(proto.Enum): It is very likely that the image belongs to the specified vertical. """ + UNKNOWN = 0 VERY_UNLIKELY = 1 UNLIKELY = 2 @@ -121,6 +125,7 @@ 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. @@ -159,6 +164,7 @@ class Type(proto.Enum): OBJECT_LOCALIZATION (19): Run localizer for object detection. """ + TYPE_UNSPECIFIED = 0 FACE_DETECTION = 1 LANDMARK_DETECTION = 2 @@ -252,10 +258,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", ) @@ -325,6 +331,7 @@ 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 @@ -404,6 +411,7 @@ class Type(proto.Enum): CHIN_RIGHT_GONION (34): Chin right gonion. """ + UNKNOWN_LANDMARK = 0 LEFT_EYE = 1 RIGHT_EYE = 2 @@ -440,10 +448,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, @@ -486,40 +494,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", ) @@ -638,15 +646,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", ) @@ -722,30 +730,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", ) @@ -809,10 +817,10 @@ class DominantColorsAnnotation(proto.Message): fraction. """ - colors: MutableSequence['ColorInfo'] = proto.RepeatedField( + colors: MutableSequence["ColorInfo"] = proto.RepeatedField( proto.MESSAGE, number=1, - message='ColorInfo', + message="ColorInfo", ) @@ -825,10 +833,10 @@ class ImageProperties(proto.Message): successfully. """ - dominant_colors: 'DominantColorsAnnotation' = proto.Field( + dominant_colors: "DominantColorsAnnotation" = proto.Field( proto.MESSAGE, number=1, - message='DominantColorsAnnotation', + message="DominantColorsAnnotation", ) @@ -872,10 +880,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", ) @@ -967,34 +975,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", ) @@ -1012,20 +1020,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", ) @@ -1105,55 +1113,57 @@ 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( - proto.MESSAGE, - number=22, - message='LocalizedObjectAnnotation', + localized_object_annotations: MutableSequence["LocalizedObjectAnnotation"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=22, + 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, @@ -1170,10 +1180,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", ) @@ -1191,15 +1201,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", ) @@ -1213,10 +1223,10 @@ class BatchAnnotateImagesRequest(proto.Message): batch. """ - requests: MutableSequence['AnnotateImageRequest'] = proto.RepeatedField( + requests: MutableSequence["AnnotateImageRequest"] = proto.RepeatedField( proto.MESSAGE, number=1, - message='AnnotateImageRequest', + message="AnnotateImageRequest", ) @@ -1229,10 +1239,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", ) @@ -1252,25 +1262,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", ) @@ -1283,10 +1293,10 @@ class AsyncAnnotateFileResponse(proto.Message): AsyncAnnotateFileRequest. """ - output_config: 'OutputConfig' = proto.Field( + output_config: "OutputConfig" = proto.Field( proto.MESSAGE, number=1, - message='OutputConfig', + message="OutputConfig", ) @@ -1300,10 +1310,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", ) @@ -1317,10 +1327,10 @@ class AsyncBatchAnnotateFilesResponse(proto.Message): AsyncBatchAnnotateFilesRequest. """ - responses: MutableSequence['AsyncAnnotateFileResponse'] = proto.RepeatedField( + responses: MutableSequence["AsyncAnnotateFileResponse"] = proto.RepeatedField( proto.MESSAGE, number=1, - message='AsyncAnnotateFileResponse', + message="AsyncAnnotateFileResponse", ) @@ -1337,10 +1347,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, @@ -1369,10 +1379,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, @@ -1440,6 +1450,7 @@ class OperationMetadata(proto.Message): The time when the operation result was last updated. """ + class State(proto.Enum): r"""Batch operation states. @@ -1455,6 +1466,7 @@ class State(proto.Enum): CANCELLED (4): The batch processing was cancelled. """ + STATE_UNSPECIFIED = 0 CREATED = 1 RUNNING = 2 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 0091ec408990..3d8dbbdf5d34 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 @@ -19,16 +19,14 @@ import proto # type: ignore -from google.cloud.vision_v1p3beta1.types import geometry -from google.cloud.vision_v1p3beta1.types import product_search_service +from google.cloud.vision_v1p3beta1.types import geometry, 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", }, ) @@ -196,15 +194,17 @@ 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( - proto.MESSAGE, - number=3, - message='ProductSearchResults.ObjectAnnotation', + object_annotations: MutableSequence["ProductSearchResults.ObjectAnnotation"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=3, + 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 e09d1ec17218..bd9cd32c2815 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 @@ -20,43 +20,44 @@ 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.protobuf import ( + field_mask_pb2, # type: ignore + timestamp_pb2, # type: ignore +) from google.rpc import status_pb2 # type: ignore - __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", }, ) @@ -269,10 +270,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, @@ -327,10 +328,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, @@ -370,10 +371,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, @@ -422,10 +423,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, @@ -480,10 +481,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, @@ -522,10 +523,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, @@ -576,10 +577,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, @@ -640,10 +641,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, @@ -794,10 +795,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, @@ -893,11 +894,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", ) @@ -919,10 +920,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", ) @@ -948,10 +949,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, @@ -978,6 +979,7 @@ 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. @@ -1000,6 +1002,7 @@ class State(proto.Enum): processed before the cancel command are output as specified in the request. """ + STATE_UNSPECIFIED = 0 PROCESSING = 1 SUCCESSFUL = 2 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 c769050195f3..ad12e61d4254 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,16 +21,15 @@ 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", }, ) @@ -82,6 +81,7 @@ 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. @@ -101,6 +101,7 @@ class BreakType(proto.Enum): LINE_BREAK (5): Line break that ends a paragraph. """ + UNKNOWN = 0 SPACE = 1 SURE_SPACE = 2 @@ -108,10 +109,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,21 +130,23 @@ class TextProperty(proto.Message): Detected start or end of a text segment. """ - detected_languages: MutableSequence['TextAnnotation.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TextAnnotation.DetectedLanguage', + detected_languages: MutableSequence["TextAnnotation.DetectedLanguage"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + 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 +173,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 +186,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, @@ -235,6 +238,7 @@ 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. @@ -252,6 +256,7 @@ class BlockType(proto.Enum): BARCODE (5): Barcode block. """ + UNKNOWN = 0 TEXT = 1 TABLE = 2 @@ -259,20 +264,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, @@ -312,20 +317,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, @@ -359,20 +364,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, @@ -406,10 +411,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 3371df697a28..7144923b02aa 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,11 +19,10 @@ import proto # type: ignore - __protobuf__ = proto.module( - package='google.cloud.vision.v1p3beta1', + package="google.cloud.vision.v1p3beta1", manifest={ - 'WebDetection', + "WebDetection", }, ) @@ -136,15 +135,19 @@ class WebPage(proto.Message): proto.STRING, number=3, ) - full_matching_images: MutableSequence['WebDetection.WebImage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='WebDetection.WebImage', + full_matching_images: MutableSequence["WebDetection.WebImage"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=4, + message="WebDetection.WebImage", + ) ) - partial_matching_images: MutableSequence['WebDetection.WebImage'] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='WebDetection.WebImage', + partial_matching_images: MutableSequence["WebDetection.WebImage"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=5, + 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 63c67b58d8fb..8b3a427c0577 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from google.cloud.vision_v1p4beta1 import gapic_version as package_version +import sys import google.api_core as api_core -import sys +from google.cloud.vision_v1p4beta1 import gapic_version as package_version __version__ = package_version.__version__ @@ -28,126 +28,122 @@ import importlib_metadata as metadata -from .services.image_annotator import ImageAnnotatorClient -from .services.image_annotator import ImageAnnotatorAsyncClient -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 .services.image_annotator import ImageAnnotatorAsyncClient, ImageAnnotatorClient +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 .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 warnings import sys + import warnings _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,116 +181,120 @@ 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/") + 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 b1663fdd632d..c7f40549e472 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 .client import ImageAnnotatorClient from .async_client import ImageAnnotatorAsyncClient +from .client import ImageAnnotatorClient __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 bc978c86493b..f11ac646d8af 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 @@ -14,41 +14,55 @@ # limitations under the License. # import logging as std_logging -from collections import OrderedDict import re -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 collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) -from google.api_core.client_options import ClientOptions +import google.protobuf 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.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.vision_v1p4beta1 import gapic_version as package_version +from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore +from google.api_core import ( + operation, # type: ignore + operation_async, # type: ignore +) from google.cloud.vision_v1p4beta1.types import image_annotator -from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport + from .client import ImageAnnotatorClient +from .transports.base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport 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 @@ -69,16 +83,30 @@ 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): @@ -93,7 +121,9 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ImageAnnotatorAsyncClient: The constructed client. """ - return ImageAnnotatorClient.from_service_account_info.__func__(ImageAnnotatorAsyncClient, info, *args, **kwargs) # type: ignore + return ImageAnnotatorClient.from_service_account_info.__func__( + ImageAnnotatorAsyncClient, info, *args, **kwargs + ) # type: ignore @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -109,12 +139,16 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ImageAnnotatorAsyncClient: The constructed client. """ - return ImageAnnotatorClient.from_service_account_file.__func__(ImageAnnotatorAsyncClient, filename, *args, **kwargs) # type: ignore + return ImageAnnotatorClient.from_service_account_file.__func__( + ImageAnnotatorAsyncClient, filename, *args, **kwargs + ) # type: ignore 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: @@ -177,12 +211,16 @@ 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: @@ -237,31 +275,43 @@ def __init__(self, *, 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. @@ -319,10 +369,14 @@ 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. @@ -336,7 +390,9 @@ 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() @@ -352,14 +408,17 @@ 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. @@ -424,10 +483,14 @@ 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. @@ -441,7 +504,9 @@ 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() @@ -457,15 +522,20 @@ 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. @@ -547,10 +617,14 @@ 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. @@ -566,7 +640,9 @@ 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() @@ -590,14 +666,19 @@ 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 @@ -668,10 +749,14 @@ 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. @@ -685,7 +770,9 @@ 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() @@ -715,12 +802,13 @@ 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__) -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +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__ = ( - "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 a2b1c6058f09..5a49828ed9a5 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 @@ -13,27 +13,38 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict -from http import HTTPStatus import json import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) -from google.cloud.vision_v1p4beta1 import gapic_version as package_version - +import google.protobuf 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.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.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.cloud.vision_v1p4beta1 import gapic_version as package_version +from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -42,16 +53,20 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore +from google.api_core import ( + operation, # type: ignore + operation_async, # type: ignore +) from google.cloud.vision_v1p4beta1.types import image_annotator -from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO + +from .transports.base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport from .transports.grpc import ImageAnnotatorGrpcTransport from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport from .transports.rest import ImageAnnotatorRestTransport @@ -64,14 +79,16 @@ class ImageAnnotatorClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _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: @@ -147,14 +164,16 @@ 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" @@ -193,8 +212,7 @@ 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) @@ -211,84 +229,132 @@ 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: @@ -320,14 +386,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio 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 @@ -340,7 +410,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # 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 @@ -365,7 +437,9 @@ 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 @@ -388,7 +462,9 @@ 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: @@ -404,17 +480,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ 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: @@ -450,15 +534,18 @@ 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 @@ -491,12 +578,16 @@ 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: @@ -551,14 +642,22 @@ def __init__(self, *, 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 @@ -569,7 +668,9 @@ def __init__(self, *, 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 @@ -578,30 +679,40 @@ def __init__(self, *, 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 " - "directly." + "When providing a transport instance, provide its scopes directly." ) 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) @@ -620,28 +731,41 @@ def __init__(self, *, ) 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. @@ -699,10 +823,14 @@ 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. @@ -731,14 +859,17 @@ 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. @@ -803,10 +934,14 @@ 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. @@ -835,15 +970,20 @@ 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. @@ -925,10 +1065,14 @@ 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. @@ -943,7 +1087,9 @@ 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() @@ -967,14 +1113,19 @@ 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 @@ -1045,10 +1196,14 @@ 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. @@ -1061,7 +1216,9 @@ 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() @@ -1099,16 +1256,11 @@ 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 d3a583db5759..1de28b3fb87a 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,20 +19,18 @@ from .base import ImageAnnotatorTransport from .grpc import ImageAnnotatorGrpcTransport from .grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport -from .rest import ImageAnnotatorRestTransport -from .rest import ImageAnnotatorRestInterceptor - +from .rest import ImageAnnotatorRestInterceptor, ImageAnnotatorRestTransport # 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 f4b7b5f8fb89..12ea8f92c5cc 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,21 @@ 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 +import google.auth # type: ignore +import google.protobuf from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, operations_v1 from google.api_core import retry as retries -from google.api_core import operations_v1 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 from google.cloud.vision_v1p4beta1.types import image_annotator -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # 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,24 +40,25 @@ 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: @@ -93,31 +93,43 @@ 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=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + 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=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + 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 @@ -133,8 +145,7 @@ 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, @@ -146,8 +157,7 @@ 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, @@ -159,8 +169,7 @@ 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, @@ -172,21 +181,20 @@ 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() @@ -196,39 +204,45 @@ 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 @@ -236,6 +250,4 @@ 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 1ead921c247c..2ad4223f8a4f 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 @@ -19,24 +19,23 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union -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.protobuf.json_format import MessageToJson -import google.protobuf.message - import grpc # type: ignore import proto # type: ignore +import google.auth # type: ignore +import google.protobuf.message +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore from google.cloud.vision_v1p4beta1.types import image_annotator -from google.longrunning import operations_pb2 # type: ignore -from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport 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,7 +45,9 @@ 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 +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.ImageAnnotator", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -78,7 +79,11 @@ 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) @@ -93,7 +98,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, @@ -118,23 +123,26 @@ 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: @@ -258,19 +266,23 @@ def __init__(self, *, ) 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. @@ -306,13 +318,12 @@ def create_channel(cls, 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 @@ -332,9 +343,12 @@ 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 @@ -350,18 +364,21 @@ def batch_annotate_images(self) -> Callable[ # 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 @@ -384,18 +401,20 @@ def batch_annotate_files(self) -> Callable[ # 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 @@ -421,18 +440,22 @@ def async_batch_annotate_images(self) -> Callable[ # 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', - request_serializer=image_annotator.AsyncBatchAnnotateImagesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, + 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 @@ -453,13 +476,15 @@ def async_batch_annotate_files(self) -> Callable[ # 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', - request_serializer=image_annotator.AsyncBatchAnnotateFilesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, + 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() @@ -469,6 +494,4 @@ 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 1ead8feda588..28d4ccb13beb 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,32 +15,31 @@ # import inspect import json -import pickle import logging as std_logging +import pickle 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 +import grpc # type: ignore +import proto # type: ignore +from grpc.experimental import aio # type: ignore + +import google.protobuf.message 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.api_core import operations_v1 -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.cloud.vision_v1p4beta1.types import image_annotator +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 grpc.experimental import aio # type: ignore - -from google.cloud.vision_v1p4beta1.types import image_annotator -from google.longrunning import operations_pb2 # type: ignore -from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO +from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport 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 @@ -48,9 +47,13 @@ _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): @@ -71,7 +74,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, @@ -82,7 +85,11 @@ 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) @@ -97,7 +104,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, @@ -127,13 +134,15 @@ 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. @@ -164,24 +173,26 @@ def create_channel(cls, 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: @@ -307,7 +318,9 @@ def __init__(self, *, 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) @@ -338,9 +351,12 @@ 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 @@ -356,18 +372,21 @@ def batch_annotate_images(self) -> Callable[ # 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 @@ -390,18 +409,21 @@ def batch_annotate_files(self) -> Callable[ # 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 @@ -427,18 +449,23 @@ def async_batch_annotate_images(self) -> Callable[ # 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', - request_serializer=image_annotator.AsyncBatchAnnotateImagesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, + 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 @@ -459,16 +486,18 @@ def async_batch_annotate_files(self) -> Callable[ # 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', - request_serializer=image_annotator.AsyncBatchAnnotateFilesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, + 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, @@ -476,8 +505,7 @@ 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, @@ -489,8 +517,7 @@ 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, @@ -502,8 +529,7 @@ 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, @@ -515,8 +541,7 @@ 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, @@ -537,6 +562,4 @@ 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 8836d99cf1cd..912b670267a3 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,33 +13,26 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import logging -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 retry as retries -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 json # type: ignore +import logging import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +from requests import __version__ as requests_version +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_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.cloud.vision_v1p4beta1.types import image_annotator from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format - -from .rest_base import _BaseImageAnnotatorRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseImageAnnotatorRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -48,6 +41,7 @@ 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 @@ -116,7 +110,15 @@ 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 @@ -124,7 +126,9 @@ def pre_async_batch_annotate_files(self, request: image_annotator.AsyncBatchAnno """ 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` @@ -137,7 +141,11 @@ def post_async_batch_annotate_files(self, response: operations_pb2.Operation) -> """ 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 @@ -152,7 +160,14 @@ def post_async_batch_annotate_files_with_metadata(self, response: operations_pb2 """ 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 @@ -160,7 +175,9 @@ def pre_async_batch_annotate_images(self, request: image_annotator.AsyncBatchAnn """ 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` @@ -173,7 +190,11 @@ def post_async_batch_annotate_images(self, response: operations_pb2.Operation) - """ 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 @@ -188,7 +209,14 @@ def post_async_batch_annotate_images_with_metadata(self, response: operations_pb """ 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 @@ -196,7 +224,9 @@ def pre_batch_annotate_files(self, request: image_annotator.BatchAnnotateFilesRe """ 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` @@ -209,7 +239,14 @@ def post_batch_annotate_files(self, response: image_annotator.BatchAnnotateFiles """ 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 @@ -224,7 +261,14 @@ def post_batch_annotate_files_with_metadata(self, response: image_annotator.Batc """ 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 @@ -232,7 +276,9 @@ def pre_batch_annotate_images(self, request: image_annotator.BatchAnnotateImages """ 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` @@ -245,7 +291,14 @@ def post_batch_annotate_images(self, response: image_annotator.BatchAnnotateImag """ 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 @@ -283,20 +336,21 @@ 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: @@ -340,10 +394,11 @@ def __init__(self, *, 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) @@ -359,23 +414,28 @@ 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") @@ -387,77 +447,91 @@ 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() - 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, @@ -466,7 +540,17 @@ def __call__(self, ) # 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. @@ -479,20 +563,24 @@ def __call__(self, 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"], @@ -501,7 +589,10 @@ def __call__(self, ) return resp - class _AsyncBatchAnnotateImages(_BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateImages, ImageAnnotatorRestStub): + class _AsyncBatchAnnotateImages( + _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateImages, + ImageAnnotatorRestStub, + ): def __hash__(self): return hash("ImageAnnotatorRestTransport.AsyncBatchAnnotateImages") @@ -513,76 +604,90 @@ 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() - 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, @@ -591,7 +696,17 @@ def __call__(self, ) # 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. @@ -604,20 +719,24 @@ def __call__(self, 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"], @@ -626,7 +745,9 @@ def __call__(self, ) return resp - class _BatchAnnotateFiles(_BaseImageAnnotatorRestTransport._BaseBatchAnnotateFiles, ImageAnnotatorRestStub): + class _BatchAnnotateFiles( + _BaseImageAnnotatorRestTransport._BaseBatchAnnotateFiles, ImageAnnotatorRestStub + ): def __hash__(self): return hash("ImageAnnotatorRestTransport.BatchAnnotateFiles") @@ -638,27 +759,29 @@ 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: @@ -680,30 +803,42 @@ def __call__(self, 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, @@ -712,7 +847,15 @@ def __call__(self, ) # 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. @@ -727,20 +870,26 @@ def __call__(self, 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"], @@ -749,7 +898,10 @@ def __call__(self, ) return resp - class _BatchAnnotateImages(_BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages, ImageAnnotatorRestStub): + class _BatchAnnotateImages( + _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages, + ImageAnnotatorRestStub, + ): def __hash__(self): return hash("ImageAnnotatorRestTransport.BatchAnnotateImages") @@ -761,27 +913,29 @@ 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: @@ -805,30 +959,42 @@ def __call__(self, 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, @@ -837,7 +1003,15 @@ def __call__(self, ) # 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. @@ -852,20 +1026,26 @@ def __call__(self, 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"], @@ -875,36 +1055,50 @@ def __call__(self, 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: @@ -914,6 +1108,4 @@ 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 60e8ac98bc3c..d450843b5b5e 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,18 +14,15 @@ # 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.cloud.vision_v1p4beta1.types import image_annotator from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport class _BaseImageAnnotatorRestTransport(ImageAnnotatorTransport): @@ -41,14 +38,16 @@ 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,7 +71,9 @@ def __init__(self, *, # 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() @@ -83,27 +84,31 @@ def __init__(self, *, 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 @@ -118,17 +123,23 @@ 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 @@ -137,20 +148,24 @@ 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 @@ -165,17 +180,23 @@ 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 @@ -184,20 +205,24 @@ 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 @@ -212,17 +237,23 @@ 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 @@ -231,20 +262,24 @@ 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 @@ -259,22 +294,26 @@ 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 ff3cc167408d..f2e4fe58e8df 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 .client import ProductSearchClient from .async_client import ProductSearchAsyncClient +from .client import ProductSearchClient __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 2155ab42d303..18e2b301a048 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 @@ -14,47 +14,62 @@ # limitations under the License. # import logging as std_logging -from collections import OrderedDict import re -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 collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) -from google.api_core.client_options import ClientOptions +import google.protobuf 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.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.vision_v1p4beta1 import gapic_version as package_version +from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore +from google.api_core import ( + operation, # type: ignore + 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.cloud.vision_v1p4beta1.types import geometry, product_search_service +from google.protobuf import ( + empty_pb2, # type: ignore + field_mask_pb2, # type: ignore + timestamp_pb2, # type: ignore +) from google.rpc import status_pb2 # type: ignore -from .transports.base import ProductSearchTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ProductSearchGrpcAsyncIOTransport + from .client import ProductSearchClient +from .transports.base import DEFAULT_CLIENT_INFO, ProductSearchTransport +from .transports.grpc_asyncio import ProductSearchGrpcAsyncIOTransport 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: @@ -92,17 +107,33 @@ 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): @@ -117,7 +148,9 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ProductSearchAsyncClient: The constructed client. """ - return ProductSearchClient.from_service_account_info.__func__(ProductSearchAsyncClient, info, *args, **kwargs) # type: ignore + return ProductSearchClient.from_service_account_info.__func__( + ProductSearchAsyncClient, info, *args, **kwargs + ) # type: ignore @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -133,12 +166,16 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ProductSearchAsyncClient: The constructed client. """ - return ProductSearchClient.from_service_account_file.__func__(ProductSearchAsyncClient, filename, *args, **kwargs) # type: ignore + return ProductSearchClient.from_service_account_file.__func__( + ProductSearchAsyncClient, filename, *args, **kwargs + ) # type: ignore 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: @@ -201,12 +238,16 @@ 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: @@ -261,33 +302,43 @@ def __init__(self, *, 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: @@ -369,10 +420,14 @@ 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. @@ -390,14 +445,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. @@ -414,14 +469,17 @@ 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: @@ -488,10 +546,14 @@ 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. @@ -505,14 +567,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. @@ -540,14 +602,17 @@ 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: @@ -613,10 +678,14 @@ 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. @@ -630,14 +699,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. @@ -654,15 +723,18 @@ 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. @@ -738,10 +810,14 @@ 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. @@ -757,14 +833,16 @@ 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. @@ -781,14 +859,17 @@ 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. @@ -842,10 +923,14 @@ 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. @@ -859,14 +944,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. @@ -880,16 +965,19 @@ 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: @@ -970,10 +1058,14 @@ 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. @@ -991,14 +1083,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. @@ -1015,14 +1107,17 @@ 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: @@ -1089,10 +1184,14 @@ 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. @@ -1106,14 +1205,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. @@ -1141,14 +1240,15 @@ 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: @@ -1209,10 +1309,14 @@ 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. @@ -1226,14 +1330,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. @@ -1250,15 +1354,18 @@ 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. @@ -1338,10 +1445,14 @@ 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. @@ -1357,14 +1468,16 @@ 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. @@ -1381,14 +1494,17 @@ 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 @@ -1443,10 +1559,14 @@ 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. @@ -1460,14 +1580,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. @@ -1481,16 +1601,19 @@ 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 @@ -1593,10 +1716,14 @@ 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. @@ -1614,14 +1741,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. @@ -1638,14 +1765,17 @@ 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 @@ -1704,10 +1834,14 @@ 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. @@ -1721,14 +1855,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. @@ -1742,14 +1876,17 @@ 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: @@ -1818,10 +1955,14 @@ 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. @@ -1835,14 +1976,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. @@ -1870,14 +2011,17 @@ 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: @@ -1942,10 +2086,14 @@ 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. @@ -1959,14 +2107,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. @@ -1983,15 +2131,18 @@ 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. @@ -2062,14 +2213,20 @@ 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 @@ -2081,14 +2238,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. @@ -2102,15 +2259,18 @@ 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 @@ -2173,14 +2333,20 @@ 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 @@ -2192,14 +2358,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. @@ -2213,14 +2379,17 @@ 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. @@ -2292,14 +2461,20 @@ 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 @@ -2309,14 +2484,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. @@ -2344,15 +2519,20 @@ 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. @@ -2442,10 +2622,14 @@ 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. @@ -2461,14 +2645,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. @@ -2493,14 +2677,17 @@ 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. @@ -2599,10 +2786,14 @@ 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. @@ -2616,14 +2807,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. @@ -2654,12 +2845,13 @@ 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__) -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +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__ = ( - "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 805bddb387c5..93ec3da47c75 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 @@ -13,27 +13,38 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict -from http import HTTPStatus import json import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) -from google.cloud.vision_v1p4beta1 import gapic_version as package_version - +import google.protobuf 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.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.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.cloud.vision_v1p4beta1 import gapic_version as package_version +from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -42,22 +53,27 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore +from google.api_core import ( + operation, # type: ignore + 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.cloud.vision_v1p4beta1.types import geometry, product_search_service +from google.protobuf import ( + empty_pb2, # type: ignore + field_mask_pb2, # type: ignore + timestamp_pb2, # type: ignore +) from google.rpc import status_pb2 # type: ignore -from .transports.base import ProductSearchTransport, DEFAULT_CLIENT_INFO + +from .transports.base import DEFAULT_CLIENT_INFO, ProductSearchTransport from .transports.grpc import ProductSearchGrpcTransport from .transports.grpc_asyncio import ProductSearchGrpcAsyncIOTransport from .transports.rest import ProductSearchRestTransport @@ -70,14 +86,16 @@ 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: @@ -169,14 +187,16 @@ 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,8 +235,7 @@ 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) @@ -233,95 +252,156 @@ 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: @@ -353,14 +433,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio 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 @@ -373,7 +457,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # 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 @@ -398,7 +484,9 @@ 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 @@ -421,7 +509,9 @@ 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,17 +527,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ 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: @@ -483,15 +581,18 @@ 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 @@ -524,12 +625,16 @@ 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: @@ -584,14 +689,22 @@ def __init__(self, *, 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 @@ -602,7 +715,9 @@ def __init__(self, *, 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 @@ -611,30 +726,40 @@ def __init__(self, *, 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 " - "directly." + "When providing a transport instance, provide its scopes directly." ) 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) @@ -653,30 +778,41 @@ def __init__(self, *, ) 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: @@ -758,10 +894,14 @@ 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. @@ -783,9 +923,7 @@ 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. @@ -802,14 +940,17 @@ 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: @@ -876,10 +1017,14 @@ 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. @@ -897,9 +1042,7 @@ 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. @@ -927,14 +1070,17 @@ 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: @@ -1000,10 +1146,14 @@ 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. @@ -1021,9 +1171,7 @@ 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. @@ -1040,15 +1188,18 @@ 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. @@ -1124,10 +1275,14 @@ 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. @@ -1147,9 +1302,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. @@ -1166,14 +1321,17 @@ 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. @@ -1227,10 +1385,14 @@ 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. @@ -1248,9 +1410,7 @@ 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. @@ -1264,16 +1424,19 @@ 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: @@ -1354,10 +1517,14 @@ 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. @@ -1379,9 +1546,7 @@ 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. @@ -1398,14 +1563,17 @@ 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: @@ -1472,10 +1640,14 @@ 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. @@ -1493,9 +1665,7 @@ 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. @@ -1523,14 +1693,15 @@ 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: @@ -1591,10 +1762,14 @@ 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. @@ -1612,9 +1787,7 @@ 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. @@ -1631,15 +1804,18 @@ 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. @@ -1719,10 +1895,14 @@ 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. @@ -1742,9 +1922,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. @@ -1761,14 +1941,17 @@ 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 @@ -1823,10 +2006,14 @@ 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. @@ -1844,9 +2031,7 @@ 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. @@ -1860,16 +2045,19 @@ 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 @@ -1972,10 +2160,14 @@ 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. @@ -1997,9 +2189,7 @@ 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. @@ -2016,14 +2206,17 @@ 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 @@ -2082,10 +2275,14 @@ 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. @@ -2103,9 +2300,7 @@ 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. @@ -2119,14 +2314,17 @@ 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: @@ -2195,10 +2393,14 @@ 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. @@ -2216,9 +2418,7 @@ 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. @@ -2246,14 +2446,17 @@ 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: @@ -2318,10 +2521,14 @@ 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. @@ -2339,9 +2546,7 @@ 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. @@ -2358,15 +2563,18 @@ 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. @@ -2437,14 +2645,20 @@ 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. @@ -2455,14 +2669,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. @@ -2476,15 +2690,18 @@ 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 @@ -2547,14 +2764,20 @@ 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. @@ -2565,14 +2788,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. @@ -2586,14 +2809,17 @@ 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. @@ -2665,14 +2891,20 @@ 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. @@ -2681,14 +2913,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. @@ -2716,15 +2948,20 @@ 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. @@ -2814,10 +3051,14 @@ 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. @@ -2837,9 +3078,7 @@ 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. @@ -2864,14 +3103,17 @@ 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. @@ -2970,10 +3212,14 @@ 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. @@ -2991,9 +3237,7 @@ 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. @@ -3032,16 +3276,11 @@ 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 7a0afcc1848e..d6d1065fd30d 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,13 +13,27 @@ # 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 @@ -44,14 +58,17 @@ 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: @@ -84,7 +101,12 @@ 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]: @@ -92,7 +114,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: @@ -112,14 +134,19 @@ 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: @@ -148,12 +175,20 @@ 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: @@ -163,7 +198,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: @@ -183,14 +218,17 @@ 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: @@ -223,7 +261,12 @@ 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]: @@ -231,7 +274,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: @@ -251,14 +294,17 @@ 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: @@ -291,8 +337,14 @@ 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: @@ -302,7 +354,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: @@ -322,14 +374,17 @@ 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: @@ -362,7 +417,12 @@ 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]: @@ -370,7 +430,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: @@ -390,14 +450,19 @@ 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: @@ -426,12 +491,20 @@ 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: @@ -441,7 +514,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: @@ -461,14 +534,17 @@ 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: @@ -497,11 +573,18 @@ 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]: @@ -509,7 +592,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: @@ -529,14 +612,19 @@ 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: @@ -565,12 +653,20 @@ 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: @@ -580,4 +676,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 f5f6aac78c26..e3bd7adc48d8 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,20 +19,18 @@ from .base import ProductSearchTransport from .grpc import ProductSearchGrpcTransport from .grpc_asyncio import ProductSearchGrpcAsyncIOTransport -from .rest import ProductSearchRestTransport -from .rest import ProductSearchRestInterceptor - +from .rest import ProductSearchRestInterceptor, ProductSearchRestTransport # 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 3477f6baaa59..9e018b77fcb2 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,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 +import google.auth # type: ignore +import google.protobuf from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, operations_v1 from google.api_core import retry as retries -from google.api_core import operations_v1 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 from google.cloud.vision_v1p4beta1.types import product_search_service -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # 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,24 +41,25 @@ 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: @@ -94,31 +94,43 @@ 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=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + 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=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + 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 @@ -134,8 +146,7 @@ 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, @@ -177,8 +188,7 @@ 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, @@ -205,8 +215,7 @@ 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, @@ -248,8 +257,7 @@ 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, @@ -276,8 +284,7 @@ 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, @@ -334,8 +341,7 @@ 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, @@ -347,8 +353,7 @@ 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, @@ -375,8 +380,7 @@ 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, @@ -387,14 +391,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() @@ -404,174 +408,207 @@ 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 @@ -579,6 +616,4 @@ 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 e9edfda1f986..7b4a484917ae 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 @@ -19,25 +19,24 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union -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.protobuf.json_format import MessageToJson -import google.protobuf.message - import grpc # type: ignore import proto # type: ignore +import google.auth # type: ignore +import google.protobuf.message +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore from google.cloud.vision_v1p4beta1.types import product_search_service -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore -from .base import ProductSearchTransport, DEFAULT_CLIENT_INFO +from google.protobuf.json_format import MessageToJson + +from .base import DEFAULT_CLIENT_INFO, ProductSearchTransport 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,7 +46,9 @@ 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 +69,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, @@ -79,7 +80,11 @@ 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) @@ -94,7 +99,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, @@ -135,23 +140,26 @@ 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: @@ -275,19 +283,23 @@ def __init__(self, *, ) 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. @@ -323,13 +335,12 @@ def create_channel(cls, 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 @@ -349,9 +360,12 @@ 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. @@ -371,18 +385,21 @@ def create_product_set(self) -> Callable[ # 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. @@ -402,18 +419,20 @@ def list_product_sets(self) -> Callable[ # 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. @@ -432,18 +451,21 @@ def get_product_set(self) -> Callable[ # 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 @@ -466,18 +488,18 @@ def update_product_set(self) -> Callable[ # 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 @@ -496,18 +518,20 @@ def delete_product_set(self) -> Callable[ # 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. @@ -531,18 +555,21 @@ def create_product(self) -> Callable[ # 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. @@ -562,18 +589,20 @@ def list_products(self) -> Callable[ # 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. @@ -592,18 +621,20 @@ def get_product(self) -> Callable[ # 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``, @@ -633,18 +664,18 @@ def update_product(self) -> Callable[ # 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 @@ -664,18 +695,21 @@ def delete_product(self) -> Callable[ # 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. @@ -711,18 +745,20 @@ def create_reference_image(self) -> Callable[ # 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. @@ -744,18 +780,21 @@ def delete_reference_image(self) -> Callable[ # 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. @@ -776,18 +815,21 @@ def list_reference_images(self) -> Callable[ # 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. @@ -806,18 +848,20 @@ def get_reference_image(self) -> Callable[ # 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 @@ -840,18 +884,22 @@ def add_product_to_product_set(self) -> Callable[ # 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', - request_serializer=product_search_service.AddProductToProductSetRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, + 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. @@ -867,18 +915,23 @@ def remove_product_from_product_set(self) -> Callable[ # 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', - request_serializer=product_search_service.RemoveProductFromProductSetRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, + 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 @@ -900,18 +953,22 @@ def list_products_in_product_set(self) -> Callable[ # 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', - request_serializer=product_search_service.ListProductsInProductSetRequest.serialize, - response_deserializer=product_search_service.ListProductsInProductSetResponse.deserialize, + 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 @@ -937,18 +994,20 @@ def import_product_sets(self) -> Callable[ # 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 @@ -989,13 +1048,13 @@ def purge_products(self) -> Callable[ # 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() @@ -1005,6 +1064,4 @@ 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 e9e7d4ee87ed..53e56434d0c8 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,33 +15,32 @@ # import inspect import json -import pickle import logging as std_logging +import pickle 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 +import grpc # type: ignore +import proto # type: ignore +from grpc.experimental import aio # type: ignore + +import google.protobuf.message 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.api_core import operations_v1 -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 proto # type: ignore -from grpc.experimental import aio # type: ignore - from google.cloud.vision_v1p4beta1.types import product_search_service -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore -from .base import ProductSearchTransport, DEFAULT_CLIENT_INFO +from google.protobuf.json_format import MessageToJson + +from .base import DEFAULT_CLIENT_INFO, ProductSearchTransport 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 @@ -49,9 +48,13 @@ _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): @@ -72,7 +75,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, @@ -83,7 +86,11 @@ 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) @@ -98,7 +105,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, @@ -144,13 +151,15 @@ 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. @@ -181,24 +190,26 @@ def create_channel(cls, 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: @@ -324,7 +335,9 @@ def __init__(self, *, 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) @@ -355,9 +368,12 @@ 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. @@ -377,18 +393,21 @@ def create_product_set(self) -> Callable[ # 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. @@ -408,18 +427,21 @@ def list_product_sets(self) -> Callable[ # 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. @@ -438,18 +460,21 @@ def get_product_set(self) -> Callable[ # 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 @@ -472,18 +497,20 @@ def update_product_set(self) -> Callable[ # 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 @@ -502,18 +529,21 @@ def delete_product_set(self) -> Callable[ # 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. @@ -537,18 +567,21 @@ def create_product(self) -> Callable[ # 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. @@ -568,18 +601,21 @@ def list_products(self) -> Callable[ # 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. @@ -598,18 +634,21 @@ def get_product(self) -> Callable[ # 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``, @@ -639,18 +678,20 @@ def update_product(self) -> Callable[ # 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 @@ -670,18 +711,21 @@ def delete_product(self) -> Callable[ # 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. @@ -717,18 +761,20 @@ def create_reference_image(self) -> Callable[ # 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. @@ -750,18 +796,21 @@ def delete_reference_image(self) -> Callable[ # 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. @@ -782,18 +831,21 @@ def list_reference_images(self) -> Callable[ # 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. @@ -812,18 +864,21 @@ def get_reference_image(self) -> Callable[ # 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 @@ -846,18 +901,23 @@ def add_product_to_product_set(self) -> Callable[ # 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', - request_serializer=product_search_service.AddProductToProductSetRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, + 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. @@ -873,18 +933,23 @@ def remove_product_from_product_set(self) -> Callable[ # 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', - request_serializer=product_search_service.RemoveProductFromProductSetRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, + 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 @@ -906,18 +971,23 @@ def list_products_in_product_set(self) -> Callable[ # 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', - request_serializer=product_search_service.ListProductsInProductSetRequest.serialize, - response_deserializer=product_search_service.ListProductsInProductSetResponse.deserialize, + 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 @@ -943,18 +1013,21 @@ def import_product_sets(self) -> Callable[ # 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 @@ -995,16 +1068,16 @@ def purge_products(self) -> Callable[ # 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, @@ -1012,8 +1085,7 @@ 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, @@ -1055,8 +1127,7 @@ 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, @@ -1083,8 +1154,7 @@ 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,8 +1196,7 @@ 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,8 +1223,7 @@ 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, @@ -1212,8 +1280,7 @@ 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, @@ -1225,8 +1292,7 @@ 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, @@ -1253,8 +1319,7 @@ 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, @@ -1280,6 +1345,4 @@ 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 1aed028974bb..fc05036bec73 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,34 +13,29 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import logging -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 retry as retries -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 json # type: ignore +import logging import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +from requests import __version__ as requests_version +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_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.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 google.protobuf import ( + empty_pb2, # type: ignore + json_format, +) - -from .rest_base import _BaseProductSearchRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseProductSearchRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -49,6 +44,7 @@ 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 @@ -217,7 +213,15 @@ 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 @@ -225,7 +229,14 @@ def pre_add_product_to_product_set(self, request: product_search_service.AddProd """ 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 @@ -233,7 +244,9 @@ def pre_create_product(self, request: product_search_service.CreateProductReques """ 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` @@ -246,7 +259,11 @@ def post_create_product(self, response: product_search_service.Product) -> produ """ 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 @@ -261,7 +278,14 @@ def post_create_product_with_metadata(self, response: product_search_service.Pro """ 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 @@ -269,7 +293,9 @@ def pre_create_product_set(self, request: product_search_service.CreateProductSe """ 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` @@ -282,7 +308,13 @@ def post_create_product_set(self, response: product_search_service.ProductSet) - """ 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 @@ -297,7 +329,14 @@ def post_create_product_set_with_metadata(self, response: product_search_service """ 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 @@ -305,7 +344,9 @@ def pre_create_reference_image(self, request: product_search_service.CreateRefer """ 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` @@ -318,7 +359,13 @@ def post_create_reference_image(self, response: product_search_service.Reference """ 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 @@ -333,7 +380,14 @@ def post_create_reference_image_with_metadata(self, response: product_search_ser """ 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 @@ -341,7 +395,14 @@ def pre_delete_product(self, request: product_search_service.DeleteProductReques """ 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 @@ -349,7 +410,14 @@ def pre_delete_product_set(self, request: product_search_service.DeleteProductSe """ 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 @@ -357,7 +425,14 @@ def pre_delete_reference_image(self, request: product_search_service.DeleteRefer """ 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 @@ -365,7 +440,9 @@ def pre_get_product(self, request: product_search_service.GetProductRequest, met """ 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` @@ -378,7 +455,11 @@ def post_get_product(self, response: product_search_service.Product) -> 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 @@ -393,7 +474,14 @@ def post_get_product_with_metadata(self, response: product_search_service.Produc """ 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 @@ -401,7 +489,9 @@ def pre_get_product_set(self, request: product_search_service.GetProductSetReque """ 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` @@ -414,7 +504,13 @@ def post_get_product_set(self, response: product_search_service.ProductSet) -> p """ 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 @@ -429,7 +525,14 @@ def post_get_product_set_with_metadata(self, response: product_search_service.Pr """ 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 @@ -437,7 +540,9 @@ def pre_get_reference_image(self, request: product_search_service.GetReferenceIm """ 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` @@ -450,7 +555,13 @@ def post_get_reference_image(self, response: product_search_service.ReferenceIma """ 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 @@ -465,7 +576,14 @@ def post_get_reference_image_with_metadata(self, response: product_search_servic """ 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 @@ -473,7 +591,9 @@ def pre_import_product_sets(self, request: product_search_service.ImportProductS """ 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` @@ -486,7 +606,11 @@ def post_import_product_sets(self, response: operations_pb2.Operation) -> operat """ 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 @@ -501,7 +625,14 @@ def post_import_product_sets_with_metadata(self, response: operations_pb2.Operat """ 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 @@ -509,7 +640,9 @@ def pre_list_products(self, request: product_search_service.ListProductsRequest, """ 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` @@ -522,7 +655,14 @@ def post_list_products(self, response: product_search_service.ListProductsRespon """ 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 @@ -537,7 +677,14 @@ def post_list_products_with_metadata(self, response: product_search_service.List """ 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 @@ -545,7 +692,9 @@ def pre_list_product_sets(self, request: product_search_service.ListProductSetsR """ 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` @@ -558,7 +707,14 @@ def post_list_product_sets(self, response: product_search_service.ListProductSet """ 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 @@ -573,7 +729,14 @@ def post_list_product_sets_with_metadata(self, response: product_search_service. """ 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 @@ -581,7 +744,9 @@ def pre_list_products_in_product_set(self, request: product_search_service.ListP """ 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` @@ -594,7 +759,14 @@ def post_list_products_in_product_set(self, response: product_search_service.Lis """ 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 @@ -609,7 +781,14 @@ def post_list_products_in_product_set_with_metadata(self, response: product_sear """ 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 @@ -617,7 +796,9 @@ def pre_list_reference_images(self, request: product_search_service.ListReferenc """ 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` @@ -630,7 +811,14 @@ def post_list_reference_images(self, response: product_search_service.ListRefere """ 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 @@ -645,7 +833,14 @@ def post_list_reference_images_with_metadata(self, response: product_search_serv """ 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 @@ -653,7 +848,9 @@ def pre_purge_products(self, request: product_search_service.PurgeProductsReques """ 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` @@ -666,7 +863,11 @@ def post_purge_products(self, response: operations_pb2.Operation) -> operations_ """ 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 @@ -681,7 +882,14 @@ def post_purge_products_with_metadata(self, response: operations_pb2.Operation, """ 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 @@ -689,7 +897,14 @@ def pre_remove_product_from_product_set(self, request: product_search_service.Re """ 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 @@ -697,7 +912,9 @@ def pre_update_product(self, request: product_search_service.UpdateProductReques """ 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` @@ -710,7 +927,11 @@ def post_update_product(self, response: product_search_service.Product) -> produ """ 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 @@ -725,7 +946,14 @@ def post_update_product_with_metadata(self, response: product_search_service.Pro """ 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 @@ -733,7 +961,9 @@ def pre_update_product_set(self, request: product_search_service.UpdateProductSe """ 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` @@ -746,7 +976,13 @@ def post_update_product_set(self, response: product_search_service.ProductSet) - """ 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 @@ -800,20 +1036,21 @@ 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: @@ -857,10 +1094,11 @@ def __init__(self, *, 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) @@ -876,23 +1114,28 @@ 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") @@ -904,69 +1147,83 @@ 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() - 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, @@ -975,14 +1232,24 @@ def __call__(self, ) # 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") @@ -994,27 +1261,29 @@ 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: @@ -1033,32 +1302,44 @@ def __call__(self, 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, @@ -1067,7 +1348,15 @@ def __call__(self, ) # 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. @@ -1082,20 +1371,24 @@ def __call__(self, 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"], @@ -1104,7 +1397,9 @@ def __call__(self, ) return resp - class _CreateProductSet(_BaseProductSearchRestTransport._BaseCreateProductSet, ProductSearchRestStub): + class _CreateProductSet( + _BaseProductSearchRestTransport._BaseCreateProductSet, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.CreateProductSet") @@ -1116,27 +1411,29 @@ 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: @@ -1162,30 +1459,42 @@ def __call__(self, 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, @@ -1194,7 +1503,15 @@ def __call__(self, ) # 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. @@ -1209,20 +1526,26 @@ def __call__(self, 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"], @@ -1231,7 +1554,9 @@ def __call__(self, ) return resp - class _CreateReferenceImage(_BaseProductSearchRestTransport._BaseCreateReferenceImage, ProductSearchRestStub): + class _CreateReferenceImage( + _BaseProductSearchRestTransport._BaseCreateReferenceImage, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.CreateReferenceImage") @@ -1243,27 +1568,29 @@ 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: @@ -1286,30 +1613,42 @@ def __call__(self, 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, @@ -1318,7 +1657,15 @@ def __call__(self, ) # 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. @@ -1333,20 +1680,26 @@ def __call__(self, 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"], @@ -1355,7 +1708,9 @@ def __call__(self, ) return resp - class _DeleteProduct(_BaseProductSearchRestTransport._BaseDeleteProduct, ProductSearchRestStub): + class _DeleteProduct( + _BaseProductSearchRestTransport._BaseDeleteProduct, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.DeleteProduct") @@ -1367,26 +1722,28 @@ 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: @@ -1401,30 +1758,40 @@ def __call__(self, 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, @@ -1433,14 +1800,23 @@ def __call__(self, ) # 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") @@ -1452,26 +1828,28 @@ 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: @@ -1488,28 +1866,38 @@ def __call__(self, 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, @@ -1518,14 +1906,23 @@ def __call__(self, ) # 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") @@ -1537,26 +1934,28 @@ 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: @@ -1573,28 +1972,38 @@ def __call__(self, 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, @@ -1603,14 +2012,23 @@ def __call__(self, ) # 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") @@ -1622,26 +2040,28 @@ 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: @@ -1660,30 +2080,44 @@ def __call__(self, 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, @@ -1692,7 +2126,14 @@ def __call__(self, ) # 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. @@ -1707,20 +2148,24 @@ def __call__(self, 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"], @@ -1729,7 +2174,9 @@ def __call__(self, ) return resp - class _GetProductSet(_BaseProductSearchRestTransport._BaseGetProductSet, ProductSearchRestStub): + class _GetProductSet( + _BaseProductSearchRestTransport._BaseGetProductSet, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.GetProductSet") @@ -1741,26 +2188,28 @@ 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: @@ -1784,30 +2233,40 @@ def __call__(self, """ - 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, @@ -1816,7 +2275,14 @@ def __call__(self, ) # 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. @@ -1831,20 +2297,26 @@ def __call__(self, 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"], @@ -1853,7 +2325,9 @@ def __call__(self, ) return resp - class _GetReferenceImage(_BaseProductSearchRestTransport._BaseGetReferenceImage, ProductSearchRestStub): + class _GetReferenceImage( + _BaseProductSearchRestTransport._BaseGetReferenceImage, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.GetReferenceImage") @@ -1865,26 +2339,28 @@ 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: @@ -1907,28 +2383,38 @@ def __call__(self, 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, @@ -1937,7 +2423,14 @@ def __call__(self, ) # 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. @@ -1952,20 +2445,26 @@ def __call__(self, 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"], @@ -1974,7 +2473,9 @@ def __call__(self, ) return resp - class _ImportProductSets(_BaseProductSearchRestTransport._BaseImportProductSets, ProductSearchRestStub): + class _ImportProductSets( + _BaseProductSearchRestTransport._BaseImportProductSets, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.ImportProductSets") @@ -1986,27 +2487,29 @@ 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: @@ -2030,30 +2533,42 @@ def __call__(self, 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, @@ -2062,7 +2577,15 @@ def __call__(self, ) # 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. @@ -2075,20 +2598,24 @@ def __call__(self, 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"], @@ -2097,7 +2624,9 @@ def __call__(self, ) return resp - class _ListProducts(_BaseProductSearchRestTransport._BaseListProducts, ProductSearchRestStub): + class _ListProducts( + _BaseProductSearchRestTransport._BaseListProducts, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.ListProducts") @@ -2109,26 +2638,28 @@ 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: @@ -2147,30 +2678,40 @@ def __call__(self, 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, @@ -2179,7 +2720,14 @@ def __call__(self, ) # 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. @@ -2194,20 +2742,26 @@ def __call__(self, 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"], @@ -2216,7 +2770,9 @@ def __call__(self, ) return resp - class _ListProductSets(_BaseProductSearchRestTransport._BaseListProductSets, ProductSearchRestStub): + class _ListProductSets( + _BaseProductSearchRestTransport._BaseListProductSets, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.ListProductSets") @@ -2228,26 +2784,28 @@ 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: @@ -2266,30 +2824,42 @@ def __call__(self, 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, @@ -2298,7 +2868,14 @@ def __call__(self, ) # 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. @@ -2313,20 +2890,26 @@ def __call__(self, 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"], @@ -2335,7 +2918,10 @@ def __call__(self, ) return resp - class _ListProductsInProductSet(_BaseProductSearchRestTransport._BaseListProductsInProductSet, ProductSearchRestStub): + class _ListProductsInProductSet( + _BaseProductSearchRestTransport._BaseListProductsInProductSet, + ProductSearchRestStub, + ): def __hash__(self): return hash("ProductSearchRestTransport.ListProductsInProductSet") @@ -2347,72 +2933,84 @@ 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() - 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, @@ -2421,7 +3019,16 @@ def __call__(self, ) # 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. @@ -2436,20 +3043,28 @@ def __call__(self, 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"], @@ -2458,7 +3073,9 @@ def __call__(self, ) return resp - class _ListReferenceImages(_BaseProductSearchRestTransport._BaseListReferenceImages, ProductSearchRestStub): + class _ListReferenceImages( + _BaseProductSearchRestTransport._BaseListReferenceImages, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.ListReferenceImages") @@ -2470,26 +3087,28 @@ 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: @@ -2510,28 +3129,38 @@ def __call__(self, 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, @@ -2540,7 +3169,14 @@ def __call__(self, ) # 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. @@ -2555,20 +3191,28 @@ def __call__(self, 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"], @@ -2577,7 +3221,9 @@ def __call__(self, ) return resp - class _PurgeProducts(_BaseProductSearchRestTransport._BasePurgeProducts, ProductSearchRestStub): + class _PurgeProducts( + _BaseProductSearchRestTransport._BasePurgeProducts, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.PurgeProducts") @@ -2589,27 +3235,29 @@ 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: @@ -2631,32 +3279,44 @@ def __call__(self, """ - 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, @@ -2665,7 +3325,15 @@ def __call__(self, ) # 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. @@ -2678,20 +3346,24 @@ def __call__(self, 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"], @@ -2700,7 +3372,10 @@ def __call__(self, ) return resp - class _RemoveProductFromProductSet(_BaseProductSearchRestTransport._BaseRemoveProductFromProductSet, ProductSearchRestStub): + class _RemoveProductFromProductSet( + _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet, + ProductSearchRestStub, + ): def __hash__(self): return hash("ProductSearchRestTransport.RemoveProductFromProductSet") @@ -2712,69 +3387,83 @@ 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() - 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, @@ -2783,14 +3472,26 @@ def __call__(self, ) # 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") @@ -2802,27 +3503,29 @@ 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: @@ -2841,32 +3544,44 @@ def __call__(self, 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, @@ -2875,7 +3590,15 @@ def __call__(self, ) # 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. @@ -2890,20 +3613,24 @@ def __call__(self, 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"], @@ -2912,7 +3639,9 @@ def __call__(self, ) return resp - class _UpdateProductSet(_BaseProductSearchRestTransport._BaseUpdateProductSet, ProductSearchRestStub): + class _UpdateProductSet( + _BaseProductSearchRestTransport._BaseUpdateProductSet, ProductSearchRestStub + ): def __hash__(self): return hash("ProductSearchRestTransport.UpdateProductSet") @@ -2924,27 +3653,29 @@ 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: @@ -2970,30 +3701,42 @@ def __call__(self, 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, @@ -3002,7 +3745,15 @@ def __call__(self, ) # 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. @@ -3017,20 +3768,26 @@ def __call__(self, 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"], @@ -3040,156 +3797,204 @@ def __call__(self, 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: @@ -3199,6 +4004,4 @@ 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 9b869a65a40d..4c22d16d951e 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,19 +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 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.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 google.protobuf import ( + empty_pb2, # type: ignore + json_format, +) + +from .base import DEFAULT_CLIENT_INFO, ProductSearchTransport class _BaseProductSearchRestTransport(ProductSearchTransport): @@ -42,14 +41,16 @@ 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,7 +74,9 @@ def __init__(self, *, # 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,33 +87,39 @@ def __init__(self, *, 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 @@ -119,17 +128,23 @@ 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 @@ -138,20 +153,24 @@ 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 @@ -166,17 +185,23 @@ 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 @@ -185,20 +210,24 @@ 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 @@ -213,17 +242,23 @@ 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 @@ -232,20 +267,24 @@ 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 @@ -260,17 +299,23 @@ 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 @@ -279,19 +324,23 @@ 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 @@ -303,11 +352,17 @@ 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 @@ -316,19 +371,23 @@ 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 @@ -340,11 +399,17 @@ 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 @@ -353,19 +418,23 @@ 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 @@ -377,11 +446,17 @@ 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 @@ -390,19 +465,23 @@ 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 @@ -414,11 +493,17 @@ 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 @@ -427,19 +512,23 @@ 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 @@ -451,11 +540,17 @@ 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 @@ -464,19 +559,23 @@ 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 @@ -488,11 +587,17 @@ 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 @@ -501,20 +606,24 @@ 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 @@ -529,17 +638,23 @@ 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 @@ -548,19 +663,23 @@ 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 @@ -572,11 +691,17 @@ 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 @@ -585,19 +710,23 @@ 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 @@ -609,11 +738,17 @@ 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 @@ -622,35 +757,47 @@ 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 @@ -659,19 +806,23 @@ 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 @@ -683,11 +834,17 @@ 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 @@ -696,20 +853,24 @@ 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 @@ -724,17 +885,23 @@ 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 @@ -743,26 +910,32 @@ 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 @@ -771,17 +944,23 @@ 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 @@ -790,20 +969,24 @@ 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 @@ -818,17 +1001,23 @@ 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 @@ -837,20 +1026,24 @@ 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 @@ -865,22 +1058,26 @@ 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 a57865defa58..bda072655d51 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 @@ -56,6 +56,7 @@ ImageSource, InputConfig, LatLongRect, + Likelihood, LocalizedObjectAnnotation, LocationInfo, OperationMetadata, @@ -64,7 +65,6 @@ SafeSearchAnnotation, TextDetectionParams, WebDetectionParams, - Likelihood, ) from .product_search import ( ProductSearchParams, @@ -116,91 +116,91 @@ ) __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 0d608f59c150..fecbfe028373 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,13 +19,12 @@ import proto # type: ignore - __protobuf__ = proto.module( - package='google.cloud.vision.v1p4beta1', + package="google.cloud.vision.v1p4beta1", manifest={ - 'FaceRecognitionParams', - 'Celebrity', - 'FaceRecognitionResult', + "FaceRecognitionParams", + "Celebrity", + "FaceRecognitionResult", }, ) @@ -87,10 +86,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 0398005bd403..88897bea5102 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,14 +19,13 @@ 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", }, ) @@ -85,15 +84,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 bcf0f829cdc9..9cc6e4e05e7b 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 @@ -19,60 +19,63 @@ 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 ( + face, + geometry, + product_search, + 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 - +from google.type import ( + color_pb2, # type: ignore + latlng_pb2, # type: ignore +) __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", }, ) @@ -95,6 +98,7 @@ class Likelihood(proto.Enum): VERY_LIKELY (5): It is very likely. """ + UNKNOWN = 0 VERY_UNLIKELY = 1 UNLIKELY = 2 @@ -122,6 +126,7 @@ 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. @@ -160,6 +165,7 @@ class Type(proto.Enum): OBJECT_LOCALIZATION (19): Run localizer for object detection. """ + TYPE_UNSPECIFIED = 0 FACE_DETECTION = 1 LANDMARK_DETECTION = 2 @@ -253,10 +259,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", ) @@ -334,6 +340,7 @@ 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 @@ -413,6 +420,7 @@ class Type(proto.Enum): CHIN_RIGHT_GONION (34): Chin right gonion. """ + UNKNOWN_LANDMARK = 0 LEFT_EYE = 1 RIGHT_EYE = 2 @@ -449,10 +457,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, @@ -495,45 +503,47 @@ 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( - proto.MESSAGE, - number=16, - message=face.FaceRecognitionResult, + recognition_result: MutableSequence[face.FaceRecognitionResult] = ( + proto.RepeatedField( + proto.MESSAGE, + number=16, + message=face.FaceRecognitionResult, + ) ) @@ -652,15 +662,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", ) @@ -736,30 +746,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", ) @@ -823,10 +833,10 @@ class DominantColorsAnnotation(proto.Message): fraction. """ - colors: MutableSequence['ColorInfo'] = proto.RepeatedField( + colors: MutableSequence["ColorInfo"] = proto.RepeatedField( proto.MESSAGE, number=1, - message='ColorInfo', + message="ColorInfo", ) @@ -839,10 +849,10 @@ class ImageProperties(proto.Message): successfully. """ - dominant_colors: 'DominantColorsAnnotation' = proto.Field( + dominant_colors: "DominantColorsAnnotation" = proto.Field( proto.MESSAGE, number=1, - message='DominantColorsAnnotation', + message="DominantColorsAnnotation", ) @@ -886,10 +896,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", ) @@ -983,19 +993,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, @@ -1007,15 +1017,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", ) @@ -1034,20 +1044,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", ) @@ -1127,55 +1137,57 @@ 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( - proto.MESSAGE, - number=22, - message='LocalizedObjectAnnotation', + localized_object_annotations: MutableSequence["LocalizedObjectAnnotation"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=22, + 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, @@ -1192,10 +1204,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", ) @@ -1209,10 +1221,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", ) @@ -1225,10 +1237,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", ) @@ -1264,20 +1276,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, @@ -1305,15 +1317,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, @@ -1338,10 +1350,10 @@ class BatchAnnotateFilesRequest(proto.Message): BatchAnnotateFilesRequest. """ - requests: MutableSequence['AnnotateFileRequest'] = proto.RepeatedField( + requests: MutableSequence["AnnotateFileRequest"] = proto.RepeatedField( proto.MESSAGE, number=1, - message='AnnotateFileRequest', + message="AnnotateFileRequest", ) @@ -1356,10 +1368,10 @@ class BatchAnnotateFilesResponse(proto.Message): BatchAnnotateFilesRequest. """ - responses: MutableSequence['AnnotateFileResponse'] = proto.RepeatedField( + responses: MutableSequence["AnnotateFileResponse"] = proto.RepeatedField( proto.MESSAGE, number=1, - message='AnnotateFileResponse', + message="AnnotateFileResponse", ) @@ -1379,25 +1391,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", ) @@ -1410,10 +1422,10 @@ class AsyncAnnotateFileResponse(proto.Message): AsyncAnnotateFileRequest. """ - output_config: 'OutputConfig' = proto.Field( + output_config: "OutputConfig" = proto.Field( proto.MESSAGE, number=1, - message='OutputConfig', + message="OutputConfig", ) @@ -1429,15 +1441,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", ) @@ -1450,10 +1462,10 @@ class AsyncBatchAnnotateImagesResponse(proto.Message): AsyncBatchAnnotateImagesRequest. """ - output_config: 'OutputConfig' = proto.Field( + output_config: "OutputConfig" = proto.Field( proto.MESSAGE, number=1, - message='OutputConfig', + message="OutputConfig", ) @@ -1467,10 +1479,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", ) @@ -1484,10 +1496,10 @@ class AsyncBatchAnnotateFilesResponse(proto.Message): AsyncBatchAnnotateFilesRequest. """ - responses: MutableSequence['AsyncAnnotateFileResponse'] = proto.RepeatedField( + responses: MutableSequence["AsyncAnnotateFileResponse"] = proto.RepeatedField( proto.MESSAGE, number=1, - message='AsyncAnnotateFileResponse', + message="AsyncAnnotateFileResponse", ) @@ -1512,10 +1524,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, @@ -1548,10 +1560,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, @@ -1628,6 +1640,7 @@ class OperationMetadata(proto.Message): The time when the operation result was last updated. """ + class State(proto.Enum): r"""Batch operation states. @@ -1643,6 +1656,7 @@ class State(proto.Enum): CANCELLED (4): The batch processing was cancelled. """ + STATE_UNSPECIFIED = 0 CREATED = 1 RUNNING = 2 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 2ef087ee72a9..20b3ddf17961 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 @@ -19,16 +19,14 @@ import proto # type: ignore -from google.cloud.vision_v1p4beta1.types import geometry -from google.cloud.vision_v1p4beta1.types import product_search_service +from google.cloud.vision_v1p4beta1.types import geometry, 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", }, ) @@ -196,15 +194,17 @@ 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( - proto.MESSAGE, - number=3, - message='ProductSearchResults.ObjectAnnotation', + object_annotations: MutableSequence["ProductSearchResults.ObjectAnnotation"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=3, + 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 7f5daeb43e57..af4c368eb0db 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 @@ -20,45 +20,46 @@ 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.protobuf import ( + field_mask_pb2, # type: ignore + timestamp_pb2, # type: ignore +) from google.rpc import status_pb2 # type: ignore - __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", }, ) @@ -277,10 +278,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, @@ -335,10 +336,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, @@ -378,10 +379,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, @@ -430,10 +431,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, @@ -488,10 +489,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, @@ -530,10 +531,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, @@ -584,10 +585,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, @@ -648,10 +649,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, @@ -802,10 +803,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, @@ -914,11 +915,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", ) @@ -940,10 +941,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", ) @@ -969,10 +970,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, @@ -999,6 +1000,7 @@ 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. @@ -1021,6 +1023,7 @@ class State(proto.Enum): processed before the cancel command are output as specified in the request. """ + STATE_UNSPECIFIED = 0 PROCESSING = 1 SUCCESSFUL = 2 @@ -1092,16 +1095,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 3135ade64f50..0eccb1718213 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,16 +21,15 @@ 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", }, ) @@ -82,6 +81,7 @@ 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. @@ -101,6 +101,7 @@ class BreakType(proto.Enum): LINE_BREAK (5): Line break that ends a paragraph. """ + UNKNOWN = 0 SPACE = 1 SURE_SPACE = 2 @@ -108,10 +109,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,21 +130,23 @@ class TextProperty(proto.Message): Detected start or end of a text segment. """ - detected_languages: MutableSequence['TextAnnotation.DetectedLanguage'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TextAnnotation.DetectedLanguage', + detected_languages: MutableSequence["TextAnnotation.DetectedLanguage"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + 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 +173,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 +186,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, @@ -235,6 +238,7 @@ 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. @@ -252,6 +256,7 @@ class BlockType(proto.Enum): BARCODE (5): Barcode block. """ + UNKNOWN = 0 TEXT = 1 TABLE = 2 @@ -259,20 +264,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, @@ -312,20 +317,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, @@ -359,20 +364,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, @@ -406,10 +411,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 e498481b45e8..e56d463dad92 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,11 +19,10 @@ import proto # type: ignore - __protobuf__ = proto.module( - package='google.cloud.vision.v1p4beta1', + package="google.cloud.vision.v1p4beta1", manifest={ - 'WebDetection', + "WebDetection", }, ) @@ -138,15 +137,19 @@ class WebPage(proto.Message): proto.STRING, number=3, ) - full_matching_images: MutableSequence['WebDetection.WebImage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='WebDetection.WebImage', + full_matching_images: MutableSequence["WebDetection.WebImage"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=4, + message="WebDetection.WebImage", + ) ) - partial_matching_images: MutableSequence['WebDetection.WebImage'] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='WebDetection.WebImage', + partial_matching_images: MutableSequence["WebDetection.WebImage"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=5, + message="WebDetection.WebImage", + ) ) class WebLabel(proto.Message): diff --git a/packages/google-cloud-vision/noxfile.py b/packages/google-cloud-vision/noxfile.py index f373cdbeff48..b68cc9fa8ccc 100644 --- a/packages/google-cloud-vision/noxfile.py +++ b/packages/google-cloud-vision/noxfile.py @@ -17,9 +17,8 @@ import pathlib import re import shutil - -from typing import Dict, List import warnings +from typing import Dict, List import nox @@ -235,7 +234,12 @@ 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( @@ -377,8 +381,10 @@ 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", ""), @@ -446,7 +452,12 @@ 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 f3def6d8a848..0288fce2c8fc 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,8 +39,7 @@ 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) @@ -52,4 +51,5 @@ 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 de2447c2a8fe..69d7b28f84a1 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,8 +39,7 @@ 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) @@ -52,4 +51,5 @@ 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 2d9a97969eb2..0953c8f53139 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,8 +39,7 @@ 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) @@ -52,4 +51,5 @@ 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 9a6cff5be93a..733d4a9d8038 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,8 +39,7 @@ 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) @@ -52,4 +51,5 @@ 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 a98771906e5a..f7785337c20e 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,8 +39,7 @@ 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) @@ -48,4 +47,5 @@ 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 388248aad182..c00c4f7c981e 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,8 +39,7 @@ 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) @@ -48,4 +47,5 @@ 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 89d7fbd9de7b..8e954c205482 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,8 +39,7 @@ 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) @@ -48,4 +47,5 @@ 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 39b49ed9eba9..82496a957f6e 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,8 +39,7 @@ 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) @@ -48,4 +47,5 @@ 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 e2f26851b314..37a13e8c63cf 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,4 +49,5 @@ 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 93f2df7c8691..c8e77ef1c3b5 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,4 +49,5 @@ 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 14073be246f6..3fb2f196e0b9 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,4 +49,5 @@ 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 bb444ccffa59..4e68449e5ccc 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,4 +49,5 @@ 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 2d683ddbb966..61f9918aa32f 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,4 +53,5 @@ 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 8253f237c1b0..12f53ed37d19 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,4 +53,5 @@ 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 d0e81b425a56..85877a0f73d1 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,4 +49,5 @@ 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 983b799ecd47..88a185f1a738 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,4 +49,5 @@ 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 9cdd62a6fb07..6d86f30a915d 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,4 +49,5 @@ 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 acbac5597910..839ee8e094ca 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,4 +49,5 @@ 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 817cde577530..ebbd0372e956 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,4 +49,5 @@ 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 f73c4b6c2bbe..243d179ab5f8 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,4 +49,5 @@ 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 459bdf6d2e94..eab3bcbdcff0 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,4 +53,5 @@ 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 4026a22a36bc..1c9153cdf335 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,4 +53,5 @@ 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 3bedd600822f..2172dba436f8 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,4 +50,5 @@ 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 372d9c38f61a..11973b8bf9cc 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,4 +50,5 @@ 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 5e6870d384c5..5d01dd759a46 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,4 +50,5 @@ 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 45f6792fd347..69da0f8447be 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,4 +50,5 @@ 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 83949638d156..a3e44d58066a 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,4 +50,5 @@ 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 01fd951f33a6..aacef907ce94 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,4 +50,5 @@ 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 a414f0986055..944f893f07ca 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,4 +50,5 @@ 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 5cf682f4967c..e393e657677f 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,4 +50,5 @@ 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 b178521747d7..695f670055e3 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,4 +53,5 @@ 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 b7b1f8a4ced1..384e392c2834 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,4 +53,5 @@ 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 dd40134fb385..6845e6296769 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,8 +39,7 @@ 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) @@ -48,4 +47,5 @@ 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 dfe4103bc0cd..4b728ede4467 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,8 +39,7 @@ 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) @@ -48,4 +47,5 @@ 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 1ee6b448db3b..eaf00bbbfd30 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,8 +39,7 @@ 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) @@ -48,4 +47,5 @@ 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 bd783b3e37ff..a875ca703bf5 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,8 +39,7 @@ 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) @@ -48,4 +47,5 @@ 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 d879bd5f1486..acd99ea568a6 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,8 +39,7 @@ 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) @@ -48,4 +47,5 @@ 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 dd08e70b8088..60823bc4200a 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,8 +39,7 @@ 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) @@ -48,4 +47,5 @@ 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 40ac1ed44fd2..8fd90858a501 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,8 +39,7 @@ 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) @@ -52,4 +51,5 @@ 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 c1de8241c32c..3ca6fbfedbef 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,8 +39,7 @@ 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) @@ -52,4 +51,5 @@ 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 5c4ddc3d8034..e54c5da9ab67 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,8 +39,7 @@ 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) @@ -48,4 +47,5 @@ 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 a58f396f7342..c0d489c5a1b6 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,8 +39,7 @@ 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) @@ -48,4 +47,5 @@ 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 5190f7742e0d..fd876fdee2d4 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,8 +39,7 @@ 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) @@ -52,4 +51,5 @@ 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 f483c5009cb8..a75fe8d24abd 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,8 +39,7 @@ 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) @@ -52,4 +51,5 @@ 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 b22f3e3151f2..980431b148bf 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,8 +39,7 @@ 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) @@ -48,4 +47,5 @@ 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 8c9ffba0b6d8..e8e7d0842423 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,8 +39,7 @@ 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) @@ -48,4 +47,5 @@ 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 793cce5a0ef0..220c7ea2cbcc 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,4 +49,5 @@ 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 3be0b86872d8..e7af9492b37b 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,4 +49,5 @@ 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 3203642ba373..bdf9bfe3b75f 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,4 +49,5 @@ 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 d123455da9ec..50e2025b7130 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,4 +49,5 @@ 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 dd6b1af2bcb7..81b6b961d184 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,4 +53,5 @@ 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 7b58c06580dd..d4074bc1f7e3 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,4 +53,5 @@ 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 17f5701d3ad9..e67b99a12ac1 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,4 +49,5 @@ 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 f1757a7f16b5..567e5add9ac4 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,4 +49,5 @@ 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 db13afceab6e..7b6742a7ea97 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,4 +49,5 @@ 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 c70f38e8a948..6616a3d5b504 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,4 +49,5 @@ 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 877f916e674f..9cc4a0f99c2e 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,4 +49,5 @@ 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 42a91a21ce71..44adc6cdea65 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,4 +49,5 @@ 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 407fbfb7f661..1b8904dbad18 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,4 +53,5 @@ 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 4c5c11dc7fba..ea7c0abfd4ff 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,4 +53,5 @@ 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 df0996ae9456..e42da64d36ae 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,4 +50,5 @@ 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 c234309dbedf..69559636904e 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,4 +50,5 @@ 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 2c468270578d..5cd13cb20fb4 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,4 +50,5 @@ 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 47c84c5e3d34..300599e5b37b 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,4 +50,5 @@ 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 9131b0695a1d..27305c8cf0bb 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,4 +50,5 @@ 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 8fa1334c17e6..292020a7eb3e 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,4 +50,5 @@ 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 e30b29e9dba4..f5ecc632e342 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,4 +50,5 @@ 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 6a6c66192b95..5108742a8d7b 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,4 +50,5 @@ 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 ee3f4f9e33ab..6e9670077ae5 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,8 +39,7 @@ 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) @@ -48,4 +47,5 @@ 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 51c68973f1bd..afa8692ccf66 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,8 +39,7 @@ 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) @@ -48,4 +47,5 @@ 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 11ff73a9c47c..3e3f7d9bdb2c 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,8 +39,7 @@ 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) @@ -48,4 +47,5 @@ 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 c4f54cac9ad2..be91ff8ceeff 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,8 +39,7 @@ 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) @@ -48,4 +47,5 @@ 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 829a0e5a2a09..e05ddd963c6e 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,8 +39,7 @@ 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) @@ -52,4 +51,5 @@ 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 1240a921b67a..67074625a366 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,8 +39,7 @@ 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) @@ -52,4 +51,5 @@ 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 6a1cc369ba00..341975808b5f 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,8 +39,7 @@ 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) @@ -52,4 +51,5 @@ 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 6743a6ef532b..54637091a18d 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,8 +39,7 @@ 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) @@ -52,4 +51,5 @@ 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 4de0bb3dd716..c98b1223966f 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,8 +39,7 @@ 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) @@ -48,4 +47,5 @@ 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 fc3f66d1a36a..37f31b2c5c4e 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,8 +39,7 @@ 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) @@ -48,4 +47,5 @@ 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 8621cc3b9391..11d539a96efc 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,8 +39,7 @@ 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) @@ -48,4 +47,5 @@ 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 441445dbe624..8e46bd3fef74 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,8 +39,7 @@ 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) @@ -48,4 +47,5 @@ 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 fdfa7de99a04..b24246920a34 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,4 +49,5 @@ 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 b22cbdf35bfe..e9dd5cd31f33 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,4 +49,5 @@ 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 6ac99ef6899a..daa31e8c03d5 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,4 +49,5 @@ 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 d9188e29914d..57f672ba98ed 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,4 +49,5 @@ 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 caf6a464b210..300af2d100de 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,4 +53,5 @@ 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 ad42aca10e78..f7f8ccdbef0f 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,4 +53,5 @@ 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 4f1715c3cc47..0ce2b320e4d2 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,4 +49,5 @@ 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 b4ebb79f24fa..020484624de2 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,4 +49,5 @@ 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 2f564173885a..0e78856cc59e 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,4 +49,5 @@ 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 290c3c1f0155..c1584428292c 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,4 +49,5 @@ 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 f5935a2bc952..11621f2ccf33 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,4 +49,5 @@ 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 85a2c25ee7c2..d8e180a86dac 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,4 +49,5 @@ 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 6f7c38959e2e..4301c81b5a67 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,4 +53,5 @@ 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 a29af665a278..642dbb853982 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,4 +53,5 @@ 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 1c650281b218..34182ade796a 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,4 +50,5 @@ 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 6b132c89723c..272032cb6344 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,4 +50,5 @@ 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 ddcf7dadee24..ff8659205c6d 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,4 +50,5 @@ 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 03237fa278af..2e3afcdfb6c6 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,4 +50,5 @@ 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 d0ec4cab57f3..87b4f830d02e 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,4 +50,5 @@ 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 8c61d3c3cc75..140c9049a9ec 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,4 +50,5 @@ 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 5b79efe5d8e2..ee2319491ad3 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,4 +50,5 @@ 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 56e82a10451c..3204df1efff3 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,4 +50,5 @@ 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 d1f6a20f5cc3..e9cddbb9b73a 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,4 +53,5 @@ 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 e4839d4ff6ac..245b41dd4549 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,4 +53,5 @@ 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 4eab864c3bad..64bdca23ca03 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,8 +39,7 @@ 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) @@ -48,4 +47,5 @@ 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 a23644a4ae2a..b5b95a923293 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,8 +39,7 @@ 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) @@ -48,4 +47,5 @@ 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 12b3ac478cb6..56ba66eeaef6 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,8 +39,7 @@ 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) @@ -48,4 +47,5 @@ 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 e9958f272eed..60fd080ea28f 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,8 +39,7 @@ 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) @@ -48,4 +47,5 @@ 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 f025cecf091e..57f4070f9c7d 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,8 +49,7 @@ "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 191773d5572d..cbf94b283c70 100644 --- a/packages/google-cloud-vision/tests/__init__.py +++ b/packages/google-cloud-vision/tests/__init__.py @@ -1,4 +1,3 @@ - # -*- 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 191773d5572d..cbf94b283c70 100644 --- a/packages/google-cloud-vision/tests/unit/__init__.py +++ b/packages/google-cloud-vision/tests/unit/__init__.py @@ -1,4 +1,3 @@ - # -*- 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 191773d5572d..cbf94b283c70 100644 --- a/packages/google-cloud-vision/tests/unit/gapic/__init__.py +++ b/packages/google-cloud-vision/tests/unit/gapic/__init__.py @@ -1,4 +1,3 @@ - # -*- 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 191773d5572d..cbf94b283c70 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,4 +1,3 @@ - # -*- 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 209c0624519f..6cd7eeb113bd 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,6 +14,7 @@ # limitations under the License. # import os + # try/except added for compatibility with python < 3.8 try: from unittest import mock @@ -21,52 +22,53 @@ except ImportError: # pragma: NO COVER import mock -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format import json import math +from collections.abc import AsyncIterable, Iterable + +import grpc import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule +from grpc.experimental import aio from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response from requests.sessions import Session + +from google.api_core import api_core_version 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 client_options +import google.auth +from google.api_core import ( + client_options, + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operation_async, # type: ignore + operations_v1, + path_template, +) 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 from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError -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.cloud.vision_v1.services.image_annotator import ( + ImageAnnotatorAsyncClient, + ImageAnnotatorClient, + transports, +) +from google.cloud.vision_v1.types import geometry, image_annotator, 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 - - CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -81,9 +83,11 @@ 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(): @@ -91,17 +95,27 @@ 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(): @@ -112,20 +126,43 @@ 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"} @@ -139,27 +176,46 @@ 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, - "auto", + "never", 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(): @@ -168,7 +224,9 @@ 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. @@ -176,7 +234,9 @@ 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 @@ -188,7 +248,9 @@ 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 @@ -200,7 +262,9 @@ 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 @@ -212,7 +276,9 @@ 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 @@ -227,83 +293,167 @@ 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) @@ -319,7 +469,8 @@ 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") @@ -332,14 +483,20 @@ 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) @@ -347,52 +504,68 @@ 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" ) @@ -408,30 +581,45 @@ 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( @@ -449,13 +637,15 @@ def test_image_annotator_client_client_options(client_class, transport_class, tr # 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, @@ -467,7 +657,7 @@ def test_image_annotator_client_client_options(client_class, transport_class, tr # 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( @@ -487,17 +677,22 @@ def test_image_annotator_client_client_options(client_class, transport_class, tr 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", @@ -506,48 +701,82 @@ def test_image_annotator_client_client_options(client_class, transport_class, tr 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 @@ -566,12 +795,22 @@ def test_image_annotator_client_mtls_env_auto(client_class, transport_class, tra # 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 @@ -592,15 +831,22 @@ def test_image_annotator_client_mtls_env_auto(client_class, transport_class, tra ) # 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, @@ -610,19 +856,31 @@ def test_image_annotator_client_mtls_env_auto(client_class, transport_class, tra ) -@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 @@ -630,18 +888,25 @@ 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 @@ -678,23 +943,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 = [ @@ -725,23 +990,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"}): @@ -757,16 +1022,27 @@ 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 @@ -776,27 +1052,50 @@ 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", @@ -819,11 +1118,19 @@ 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. @@ -831,27 +1138,40 @@ 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, @@ -860,24 +1180,40 @@ def test_image_annotator_client_client_options_scopes(client_class, transport_cl 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, @@ -886,11 +1222,14 @@ def test_image_annotator_client_client_options_credentials_file(client_class, tr 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, @@ -905,23 +1244,38 @@ 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, @@ -931,13 +1285,13 @@ def test_image_annotator_client_create_channel_credentials_file(client_class, tr ) # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object(grpc_helpers, "create_channel") as create_channel, + ): creds = ga_credentials.AnonymousCredentials() file_creds = ga_credentials.AnonymousCredentials() load_creds.return_value = (file_creds, None) @@ -949,9 +1303,9 @@ def test_image_annotator_client_create_channel_credentials_file(client_class, tr 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, @@ -962,11 +1316,14 @@ def test_image_annotator_client_create_channel_credentials_file(client_class, tr ) -@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, @@ -978,11 +1335,10 @@ 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. @@ -1000,28 +1356,31 @@ 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 @@ -1036,12 +1395,19 @@ 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) @@ -1054,8 +1420,11 @@ 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: @@ -1069,12 +1438,17 @@ async def test_batch_annotate_images_async_use_cached_wrapped_rpc(transport: str 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) @@ -1088,8 +1462,12 @@ async def test_batch_annotate_images_async_use_cached_wrapped_rpc(transport: str 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, @@ -1101,11 +1479,12 @@ async def test_batch_annotate_images_async(transport: str = 'grpc_asyncio', requ # 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. @@ -1130,14 +1509,18 @@ 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 @@ -1145,7 +1528,11 @@ 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 @@ -1159,9 +1546,14 @@ 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( @@ -1170,16 +1562,22 @@ 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 @@ -1187,9 +1585,14 @@ 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( @@ -1201,15 +1604,22 @@ 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, @@ -1221,11 +1631,10 @@ 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. @@ -1243,28 +1652,31 @@ 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 @@ -1279,12 +1691,18 @@ 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) @@ -1297,8 +1715,11 @@ 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: @@ -1312,12 +1733,17 @@ async def test_batch_annotate_files_async_use_cached_wrapped_rpc(transport: str 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) @@ -1331,8 +1757,12 @@ async def test_batch_annotate_files_async_use_cached_wrapped_rpc(transport: str 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, @@ -1344,11 +1774,12 @@ async def test_batch_annotate_files_async(transport: str = 'grpc_asyncio', reque # 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. @@ -1373,14 +1804,20 @@ 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 @@ -1388,7 +1825,13 @@ 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 @@ -1402,9 +1845,16 @@ 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( @@ -1413,16 +1863,24 @@ 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 @@ -1430,9 +1888,16 @@ 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( @@ -1444,15 +1909,24 @@ 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, @@ -1464,10 +1938,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. @@ -1485,28 +1959,31 @@ 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 @@ -1521,12 +1998,19 @@ 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) @@ -1544,8 +2028,11 @@ 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: @@ -1559,12 +2046,17 @@ async def test_async_batch_annotate_images_async_use_cached_wrapped_rpc(transpor 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) @@ -1583,8 +2075,12 @@ async def test_async_batch_annotate_images_async_use_cached_wrapped_rpc(transpor 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, @@ -1596,11 +2092,11 @@ async def test_async_batch_annotate_images_async(transport: str = 'grpc_asyncio' # 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) @@ -1626,15 +2122,21 @@ 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 @@ -1642,10 +2144,16 @@ 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 @@ -1659,10 +2167,17 @@ 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( @@ -1671,19 +2186,25 @@ 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 @@ -1691,12 +2212,19 @@ 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( @@ -1708,16 +2236,25 @@ 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, @@ -1729,10 +2266,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. @@ -1750,28 +2287,31 @@ 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 @@ -1786,12 +2326,19 @@ 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) @@ -1809,8 +2356,11 @@ 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: @@ -1824,12 +2374,17 @@ async def test_async_batch_annotate_files_async_use_cached_wrapped_rpc(transport 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) @@ -1848,8 +2403,12 @@ async def test_async_batch_annotate_files_async_use_cached_wrapped_rpc(transport 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, @@ -1861,11 +2420,11 @@ async def test_async_batch_annotate_files_async(transport: str = 'grpc_asyncio', # 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) @@ -1891,14 +2450,20 @@ 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 @@ -1906,7 +2471,13 @@ 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 @@ -1920,9 +2491,16 @@ 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( @@ -1931,18 +2509,24 @@ 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 @@ -1950,9 +2534,16 @@ 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( @@ -1964,7 +2555,13 @@ 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") + ) + ) + ], ) @@ -1982,12 +2579,19 @@ 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) @@ -2002,52 +2606,57 @@ 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() @@ -2057,24 +2666,24 @@ def test_batch_annotate_images_rest_required_fields(request_type=image_annotator 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(): @@ -2084,7 +2693,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() @@ -2093,7 +2702,11 @@ 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) @@ -2103,7 +2716,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"} @@ -2113,10 +2726,12 @@ 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, @@ -2127,7 +2742,11 @@ 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") + ) + ], ) @@ -2145,12 +2764,18 @@ 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) @@ -2165,52 +2790,57 @@ 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() @@ -2220,24 +2850,24 @@ def test_batch_annotate_files_rest_required_fields(request_type=image_annotator. 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(): @@ -2247,7 +2877,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() @@ -2256,7 +2886,13 @@ 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) @@ -2266,7 +2902,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"} @@ -2276,10 +2912,12 @@ 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, @@ -2290,7 +2928,13 @@ 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") + ) + ) + ], ) @@ -2308,12 +2952,19 @@ 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) @@ -2332,76 +2983,89 @@ 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(): @@ -2411,17 +3075,23 @@ 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) @@ -2429,7 +3099,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"} @@ -2439,10 +3109,12 @@ 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, @@ -2453,8 +3125,14 @@ 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") + ), ) @@ -2472,12 +3150,19 @@ 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) @@ -2496,76 +3181,81 @@ 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(): @@ -2575,16 +3265,22 @@ 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) @@ -2592,7 +3288,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"} @@ -2602,10 +3298,12 @@ 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, @@ -2616,7 +3314,13 @@ 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") + ) + ) + ], ) @@ -2658,8 +3362,7 @@ 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. @@ -2681,6 +3384,7 @@ 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( @@ -2695,18 +3399,23 @@ 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() @@ -2716,8 +3425,7 @@ 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 @@ -2732,8 +3440,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) @@ -2755,8 +3463,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) @@ -2778,9 +3486,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. @@ -2801,9 +3509,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. @@ -2823,8 +3531,7 @@ 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 @@ -2840,11 +3547,12 @@ 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. @@ -2866,11 +3574,12 @@ 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. @@ -2892,11 +3601,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) @@ -2919,11 +3628,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) @@ -2942,20 +3651,24 @@ 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() @@ -2964,14 +3677,16 @@ def test_batch_annotate_images_rest_bad_request(request_type=image_annotator.Bat 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 @@ -2979,10 +3694,9 @@ 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() @@ -2991,7 +3705,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) @@ -3004,19 +3718,32 @@ 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", @@ -3027,39 +3754,54 @@ 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() @@ -3068,14 +3810,16 @@ def test_batch_annotate_files_rest_bad_request(request_type=image_annotator.Batc 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 @@ -3083,10 +3827,9 @@ 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() @@ -3095,7 +3838,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) @@ -3108,19 +3851,32 @@ 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", @@ -3131,39 +3887,54 @@ 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() @@ -3172,14 +3943,16 @@ def test_async_batch_annotate_images_rest_bad_request(request_type=image_annotat 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 @@ -3187,15 +3960,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) @@ -3208,20 +3981,33 @@ 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", @@ -3236,7 +4022,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"), ] @@ -3244,27 +4030,37 @@ 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() @@ -3273,14 +4069,16 @@ def test_async_batch_annotate_files_rest_bad_request(request_type=image_annotato 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 @@ -3288,15 +4086,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) @@ -3309,20 +4107,33 @@ 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", @@ -3337,7 +4148,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"), ] @@ -3345,26 +4156,39 @@ 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() @@ -3373,20 +4197,23 @@ def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperation 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() @@ -3394,7 +4221,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"} @@ -3404,10 +4231,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 @@ -3422,8 +4249,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. @@ -3444,8 +4271,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. @@ -3466,8 +4293,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. @@ -3488,8 +4315,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. @@ -3510,12 +4337,13 @@ 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( @@ -3526,18 +4354,21 @@ 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(), @@ -3546,11 +4377,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): @@ -3566,7 +4397,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): @@ -3575,26 +4406,39 @@ 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() @@ -3603,15 +4447,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, ) @@ -3626,12 +4470,15 @@ 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", ) @@ -3645,39 +4492,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( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: + 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", @@ -3685,9 +4532,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, @@ -3698,10 +4545,14 @@ 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. @@ -3710,7 +4561,7 @@ def test_image_annotator_grpc_transport_client_cert_source_for_mtls( 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", @@ -3731,61 +4582,77 @@ def test_image_annotator_grpc_transport_client_cert_source_for_mtls( 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() @@ -3809,8 +4676,10 @@ 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( @@ -3823,7 +4692,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( @@ -3838,12 +4707,22 @@ 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 @@ -3852,7 +4731,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", @@ -3882,17 +4761,23 @@ 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() @@ -3923,7 +4808,7 @@ def test_image_annotator_transport_channel_mtls_with_adc( def test_image_annotator_grpc_lro_client(): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) transport = client.transport @@ -3940,7 +4825,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 @@ -3958,7 +4843,11 @@ 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 @@ -3975,11 +4864,18 @@ 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 @@ -3996,9 +4892,12 @@ 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 @@ -4013,9 +4912,12 @@ 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 @@ -4030,9 +4932,12 @@ 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 @@ -4047,9 +4952,12 @@ 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 @@ -4064,10 +4972,14 @@ 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 @@ -4087,14 +4999,18 @@ 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(), @@ -4105,7 +5021,8 @@ 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, @@ -4124,10 +5041,13 @@ 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, @@ -4149,6 +5069,7 @@ 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(), @@ -4171,7 +5092,12 @@ 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( @@ -4196,7 +5122,11 @@ 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( @@ -4213,6 +5143,8 @@ def test_get_operation_from_dict(): } ) call.assert_called() + + @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = ImageAnnotatorAsyncClient( @@ -4234,10 +5166,11 @@ 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() @@ -4246,10 +5179,11 @@ 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() @@ -4257,10 +5191,11 @@ 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() @@ -4268,13 +5203,12 @@ 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: @@ -4283,10 +5217,14 @@ 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 @@ -4301,7 +5239,9 @@ 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 a0413eb168ed..710705ee4cbc 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,6 +14,7 @@ # limitations under the License. # import os + # try/except added for compatibility with python < 3.8 try: from unittest import mock @@ -21,56 +22,60 @@ except ImportError: # pragma: NO COVER import mock -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format import json import math +from collections.abc import AsyncIterable, Iterable + +import grpc import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule +from grpc.experimental import aio from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response from requests.sessions import Session + +from google.api_core import api_core_version 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 client_options +import google.auth +from google.api_core import ( + client_options, + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operation_async, # type: ignore + operations_v1, + path_template, +) 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 from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError -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.cloud.vision_v1.services.product_search import ( + ProductSearchAsyncClient, + ProductSearchClient, + pagers, + transports, +) +from google.cloud.vision_v1.types import geometry, 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.protobuf import ( + any_pb2, # type: ignore + empty_pb2, # type: ignore + field_mask_pb2, # type: ignore + timestamp_pb2, # type: ignore +) from google.rpc import status_pb2 # type: ignore -import google.auth - - CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -85,9 +90,11 @@ 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,17 +102,27 @@ 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,11 +133,26 @@ 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) @@ -129,7 +161,11 @@ 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"} @@ -143,27 +179,46 @@ 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, - "auto", + "never", 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(): @@ -172,7 +227,9 @@ 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. @@ -180,7 +237,9 @@ 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 @@ -192,7 +251,9 @@ 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 @@ -204,7 +265,9 @@ 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 @@ -216,7 +279,9 @@ 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 @@ -231,83 +296,167 @@ 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) @@ -323,7 +472,8 @@ 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") @@ -336,14 +486,20 @@ 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) @@ -351,52 +507,68 @@ 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" ) @@ -412,30 +584,45 @@ 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( @@ -453,13 +640,15 @@ def test_product_search_client_client_options(client_class, transport_class, tra # 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, @@ -471,7 +660,7 @@ def test_product_search_client_client_options(client_class, transport_class, tra # 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( @@ -491,17 +680,22 @@ def test_product_search_client_client_options(client_class, transport_class, tra 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", @@ -510,48 +704,82 @@ def test_product_search_client_client_options(client_class, transport_class, tra 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 @@ -570,12 +798,22 @@ def test_product_search_client_mtls_env_auto(client_class, transport_class, tran # 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 @@ -596,15 +834,22 @@ def test_product_search_client_mtls_env_auto(client_class, transport_class, tran ) # 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, @@ -614,19 +859,31 @@ def test_product_search_client_mtls_env_auto(client_class, transport_class, tran ) -@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 @@ -634,18 +891,25 @@ 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 @@ -682,23 +946,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 = [ @@ -729,23 +993,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"}): @@ -761,16 +1025,27 @@ 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 @@ -780,27 +1055,50 @@ 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", @@ -823,11 +1121,19 @@ 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. @@ -835,27 +1141,40 @@ 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, @@ -864,24 +1183,40 @@ def test_product_search_client_client_options_scopes(client_class, transport_cla 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, @@ -890,11 +1225,14 @@ def test_product_search_client_client_options_credentials_file(client_class, tra 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, @@ -909,23 +1247,38 @@ 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, @@ -935,13 +1288,13 @@ def test_product_search_client_create_channel_credentials_file(client_class, tra ) # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object(grpc_helpers, "create_channel") as create_channel, + ): creds = ga_credentials.AnonymousCredentials() file_creds = ga_credentials.AnonymousCredentials() load_creds.return_value = (file_creds, None) @@ -953,9 +1306,9 @@ def test_product_search_client_create_channel_credentials_file(client_class, tra 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, @@ -966,11 +1319,14 @@ def test_product_search_client_create_channel_credentials_file(client_class, tra ) -@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, @@ -982,12 +1338,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) @@ -999,8 +1355,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(): @@ -1008,30 +1364,33 @@ 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 @@ -1046,12 +1405,18 @@ 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) @@ -1064,8 +1429,11 @@ 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: @@ -1079,12 +1447,17 @@ async def test_create_product_set_async_use_cached_wrapped_rpc(transport: str = 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) @@ -1098,8 +1471,12 @@ async def test_create_product_set_async_use_cached_wrapped_rpc(transport: str = 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, @@ -1111,13 +1488,15 @@ async def test_create_product_set_async(transport: str = 'grpc_asyncio', request # 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. @@ -1128,14 +1507,15 @@ async def test_create_product_set_async(transport: str = 'grpc_asyncio', 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.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(), @@ -1145,12 +1525,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) @@ -1162,9 +1542,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 @@ -1177,13 +1557,15 @@ 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. @@ -1194,9 +1576,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(): @@ -1206,16 +1588,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 @@ -1223,13 +1605,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 @@ -1243,11 +1625,12 @@ 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( @@ -1256,18 +1639,20 @@ 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 @@ -1275,15 +1660,16 @@ 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( @@ -1295,17 +1681,20 @@ 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, @@ -1317,11 +1706,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) @@ -1333,7 +1722,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(): @@ -1341,30 +1730,33 @@ 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 @@ -1383,8 +1775,12 @@ 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) @@ -1397,8 +1793,11 @@ 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: @@ -1412,12 +1811,17 @@ async def test_list_product_sets_async_use_cached_wrapped_rpc(transport: str = " 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) @@ -1431,8 +1835,12 @@ async def test_list_product_sets_async_use_cached_wrapped_rpc(transport: str = " 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, @@ -1444,12 +1852,14 @@ async def test_list_product_sets_async(transport: str = 'grpc_asyncio', request_ # 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. @@ -1460,13 +1870,14 @@ async def test_list_product_sets_async(transport: str = 'grpc_asyncio', request_ # 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(), @@ -1476,12 +1887,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) @@ -1493,9 +1904,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 @@ -1508,13 +1919,15 @@ 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. @@ -1525,9 +1938,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(): @@ -1537,14 +1950,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 @@ -1552,7 +1965,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 @@ -1566,9 +1979,10 @@ 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( @@ -1577,16 +1991,18 @@ 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 @@ -1594,9 +2010,10 @@ 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( @@ -1608,7 +2025,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", ) @@ -1620,8 +2037,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( @@ -1630,17 +2047,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=[ @@ -1655,9 +2072,7 @@ 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) @@ -1667,8 +2082,9 @@ 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(), @@ -1677,8 +2093,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( @@ -1687,17 +2103,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=[ @@ -1708,9 +2124,10 @@ 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( @@ -1719,8 +2136,10 @@ 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( @@ -1729,17 +2148,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=[ @@ -1749,15 +2168,16 @@ 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 @@ -1768,8 +2188,10 @@ 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( @@ -1778,17 +2200,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=[ @@ -1801,18 +2223,22 @@ 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, @@ -1823,13 +2249,11 @@ 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) @@ -1841,8 +2265,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(): @@ -1850,28 +2274,29 @@ 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 @@ -1890,7 +2315,9 @@ 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) @@ -1904,8 +2331,11 @@ 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: @@ -1919,12 +2349,17 @@ async def test_get_product_set_async_use_cached_wrapped_rpc(transport: str = "gr 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) @@ -1938,8 +2373,12 @@ async def test_get_product_set_async_use_cached_wrapped_rpc(transport: str = "gr 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, @@ -1950,14 +2389,14 @@ async def test_get_product_set_async(transport: str = 'grpc_asyncio', request_ty 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. @@ -1968,14 +2407,15 @@ async def test_get_product_set_async(transport: str = 'grpc_asyncio', request_ty # 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(), @@ -1985,12 +2425,10 @@ 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) @@ -2002,9 +2440,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 @@ -2017,13 +2455,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. @@ -2034,9 +2472,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(): @@ -2045,15 +2483,13 @@ 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 @@ -2061,7 +2497,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 @@ -2075,9 +2511,10 @@ 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( @@ -2085,17 +2522,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 @@ -2103,9 +2540,10 @@ 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( @@ -2117,15 +2555,18 @@ 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, @@ -2137,12 +2578,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) @@ -2154,8 +2595,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(): @@ -2163,25 +2604,26 @@ 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, @@ -2197,12 +2639,18 @@ 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) @@ -2215,8 +2663,11 @@ 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: @@ -2230,12 +2681,17 @@ async def test_update_product_set_async_use_cached_wrapped_rpc(transport: str = 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) @@ -2249,8 +2705,12 @@ async def test_update_product_set_async_use_cached_wrapped_rpc(transport: str = 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, @@ -2262,13 +2722,15 @@ async def test_update_product_set_async(transport: str = 'grpc_asyncio', request # 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. @@ -2279,14 +2741,15 @@ async def test_update_product_set_async(transport: str = 'grpc_asyncio', 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.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(), @@ -2296,12 +2759,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) @@ -2313,9 +2776,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 @@ -2328,13 +2791,15 @@ 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. @@ -2345,9 +2810,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(): @@ -2357,15 +2822,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 @@ -2373,10 +2838,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 @@ -2390,10 +2855,11 @@ 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( @@ -2402,17 +2868,19 @@ 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 @@ -2420,12 +2888,13 @@ 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( @@ -2437,16 +2906,19 @@ 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, @@ -2458,8 +2930,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) @@ -2479,28 +2951,31 @@ 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 @@ -2515,12 +2990,18 @@ 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) @@ -2533,8 +3014,11 @@ 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: @@ -2548,12 +3032,17 @@ async def test_delete_product_set_async_use_cached_wrapped_rpc(transport: str = 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) @@ -2567,8 +3056,12 @@ async def test_delete_product_set_async_use_cached_wrapped_rpc(transport: str = 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, @@ -2580,8 +3073,8 @@ async def test_delete_product_set_async(transport: str = 'grpc_asyncio', request # 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) @@ -2600,6 +3093,7 @@ async def test_delete_product_set_async(transport: str = 'grpc_asyncio', request 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(), @@ -2609,12 +3103,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) @@ -2626,9 +3120,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 @@ -2641,12 +3135,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) @@ -2658,9 +3152,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(): @@ -2670,14 +3164,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 @@ -2685,7 +3179,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 @@ -2699,9 +3193,10 @@ 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( @@ -2710,8 +3205,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 @@ -2719,7 +3214,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 @@ -2727,9 +3222,10 @@ 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( @@ -2741,15 +3237,18 @@ 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, @@ -2760,15 +3259,13 @@ 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) @@ -2780,10 +3277,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(): @@ -2791,30 +3288,31 @@ 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 @@ -2833,7 +3331,9 @@ 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) @@ -2847,8 +3347,11 @@ 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: @@ -2862,12 +3365,17 @@ async def test_create_product_async_use_cached_wrapped_rpc(transport: str = "grp 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) @@ -2881,8 +3389,12 @@ async def test_create_product_async_use_cached_wrapped_rpc(transport: str = "grp 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, @@ -2893,16 +3405,16 @@ async def test_create_product_async(transport: str = 'grpc_asyncio', request_typ 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. @@ -2913,16 +3425,17 @@ async def test_create_product_async(transport: str = 'grpc_asyncio', request_typ # 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(), @@ -2932,12 +3445,10 @@ 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) @@ -2949,9 +3460,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 @@ -2964,13 +3475,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. @@ -2981,9 +3492,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(): @@ -2992,17 +3503,15 @@ 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 @@ -3010,13 +3519,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 @@ -3030,11 +3539,12 @@ 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( @@ -3042,19 +3552,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 @@ -3062,15 +3572,16 @@ 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( @@ -3082,17 +3593,20 @@ 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, @@ -3103,12 +3617,10 @@ 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) @@ -3120,7 +3632,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(): @@ -3128,30 +3640,31 @@ 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 @@ -3170,7 +3683,9 @@ 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) @@ -3184,8 +3699,11 @@ 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: @@ -3199,12 +3717,17 @@ async def test_list_products_async_use_cached_wrapped_rpc(transport: str = "grpc 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) @@ -3218,8 +3741,12 @@ async def test_list_products_async_use_cached_wrapped_rpc(transport: str = "grpc 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, @@ -3230,13 +3757,13 @@ async def test_list_products_async(transport: str = 'grpc_asyncio', request_type 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. @@ -3247,13 +3774,14 @@ async def test_list_products_async(transport: str = 'grpc_asyncio', request_type # 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(), @@ -3263,12 +3791,10 @@ 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) @@ -3280,9 +3806,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 @@ -3295,13 +3821,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. @@ -3312,9 +3838,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(): @@ -3323,15 +3849,13 @@ 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 @@ -3339,7 +3863,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 @@ -3353,9 +3877,10 @@ 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( @@ -3363,17 +3888,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 @@ -3381,9 +3906,10 @@ 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( @@ -3395,7 +3921,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", ) @@ -3406,9 +3932,7 @@ 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( @@ -3417,17 +3941,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=[ @@ -3442,9 +3966,7 @@ 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) @@ -3454,8 +3976,9 @@ 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(), @@ -3463,9 +3986,7 @@ 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( @@ -3474,17 +3995,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=[ @@ -3495,9 +4016,10 @@ 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( @@ -3506,8 +4028,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( @@ -3516,17 +4038,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=[ @@ -3536,15 +4058,16 @@ 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 @@ -3555,8 +4078,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( @@ -3565,17 +4088,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=[ @@ -3588,18 +4111,22 @@ 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, @@ -3610,15 +4137,13 @@ 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) @@ -3630,10 +4155,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(): @@ -3641,28 +4166,29 @@ 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 @@ -3681,7 +4207,9 @@ 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) @@ -3695,8 +4223,11 @@ 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: @@ -3710,12 +4241,17 @@ async def test_get_product_async_use_cached_wrapped_rpc(transport: str = "grpc_a 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) @@ -3729,8 +4265,12 @@ async def test_get_product_async_use_cached_wrapped_rpc(transport: str = "grpc_a 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, @@ -3741,16 +4281,16 @@ async def test_get_product_async(transport: str = 'grpc_asyncio', request_type=p 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. @@ -3761,16 +4301,17 @@ async def test_get_product_async(transport: str = 'grpc_asyncio', request_type=p # 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(), @@ -3780,12 +4321,10 @@ 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) @@ -3797,9 +4336,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 @@ -3812,13 +4351,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. @@ -3829,9 +4368,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(): @@ -3840,15 +4379,13 @@ 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 @@ -3856,7 +4393,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 @@ -3870,9 +4407,10 @@ 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( @@ -3880,17 +4418,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 @@ -3898,9 +4436,10 @@ 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( @@ -3912,15 +4451,18 @@ 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, @@ -3931,15 +4473,13 @@ 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) @@ -3951,10 +4491,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(): @@ -3962,25 +4502,24 @@ 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, @@ -4000,7 +4539,9 @@ 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) @@ -4014,8 +4555,11 @@ 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: @@ -4029,12 +4573,17 @@ async def test_update_product_async_use_cached_wrapped_rpc(transport: str = "grp 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) @@ -4048,8 +4597,12 @@ async def test_update_product_async_use_cached_wrapped_rpc(transport: str = "grp 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, @@ -4060,16 +4613,16 @@ async def test_update_product_async(transport: str = 'grpc_asyncio', request_typ 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. @@ -4080,16 +4633,17 @@ async def test_update_product_async(transport: str = 'grpc_asyncio', request_typ # 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(), @@ -4099,12 +4653,10 @@ 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) @@ -4116,9 +4668,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 @@ -4131,13 +4683,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. @@ -4148,9 +4700,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(): @@ -4159,16 +4711,14 @@ 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 @@ -4176,10 +4726,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 @@ -4193,10 +4743,11 @@ 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( @@ -4204,18 +4755,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 @@ -4223,12 +4774,13 @@ 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( @@ -4240,16 +4792,19 @@ 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, @@ -4260,9 +4815,7 @@ 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) @@ -4282,28 +4835,29 @@ 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 @@ -4322,7 +4876,9 @@ 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) @@ -4336,8 +4892,11 @@ 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: @@ -4351,12 +4910,17 @@ async def test_delete_product_async_use_cached_wrapped_rpc(transport: str = "grp 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) @@ -4370,8 +4934,12 @@ async def test_delete_product_async_use_cached_wrapped_rpc(transport: str = "grp 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, @@ -4382,9 +4950,7 @@ async def test_delete_product_async(transport: str = 'grpc_asyncio', request_typ 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) @@ -4403,6 +4969,7 @@ async def test_delete_product_async(transport: str = 'grpc_asyncio', request_typ 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(), @@ -4412,12 +4979,10 @@ 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) @@ -4429,9 +4994,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 @@ -4444,12 +5009,10 @@ 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) @@ -4461,9 +5024,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(): @@ -4472,15 +5035,13 @@ 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 @@ -4488,7 +5049,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 @@ -4502,9 +5063,10 @@ 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( @@ -4512,9 +5074,7 @@ 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 @@ -4522,7 +5082,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 @@ -4530,9 +5090,10 @@ 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( @@ -4544,15 +5105,18 @@ 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, @@ -4564,12 +5128,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) @@ -4581,8 +5145,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(): @@ -4590,30 +5154,33 @@ 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 @@ -4628,12 +5195,19 @@ 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) @@ -4646,8 +5220,11 @@ 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: @@ -4661,12 +5238,17 @@ async def test_create_reference_image_async_use_cached_wrapped_rpc(transport: st 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) @@ -4680,8 +5262,12 @@ async def test_create_reference_image_async_use_cached_wrapped_rpc(transport: st 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, @@ -4693,13 +5279,15 @@ async def test_create_reference_image_async(transport: str = 'grpc_asyncio', req # 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. @@ -4710,14 +5298,15 @@ async def test_create_reference_image_async(transport: str = 'grpc_asyncio', req # 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(), @@ -4727,12 +5316,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) @@ -4744,9 +5333,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 @@ -4759,13 +5348,15 @@ 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. @@ -4776,9 +5367,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(): @@ -4788,16 +5379,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 @@ -4805,13 +5396,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 @@ -4825,11 +5416,12 @@ 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( @@ -4838,18 +5430,20 @@ 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 @@ -4857,15 +5451,16 @@ 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( @@ -4877,17 +5472,20 @@ 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, @@ -4899,8 +5497,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) @@ -4920,28 +5518,31 @@ 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 @@ -4956,12 +5557,19 @@ 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) @@ -4974,8 +5582,11 @@ 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: @@ -4989,12 +5600,17 @@ async def test_delete_reference_image_async_use_cached_wrapped_rpc(transport: st 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) @@ -5008,8 +5624,12 @@ async def test_delete_reference_image_async_use_cached_wrapped_rpc(transport: st 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, @@ -5021,8 +5641,8 @@ async def test_delete_reference_image_async(transport: str = 'grpc_asyncio', req # 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) @@ -5041,6 +5661,7 @@ async def test_delete_reference_image_async(transport: str = 'grpc_asyncio', req 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(), @@ -5050,12 +5671,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) @@ -5067,9 +5688,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 @@ -5082,12 +5703,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) @@ -5099,9 +5720,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(): @@ -5111,14 +5732,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 @@ -5126,7 +5747,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 @@ -5140,9 +5761,10 @@ 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( @@ -5151,8 +5773,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 @@ -5160,7 +5782,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 @@ -5168,9 +5790,10 @@ 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( @@ -5182,15 +5805,18 @@ 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, @@ -5202,12 +5828,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) @@ -5220,7 +5846,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(): @@ -5228,30 +5854,33 @@ 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 @@ -5266,12 +5895,19 @@ 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) @@ -5284,8 +5920,11 @@ 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: @@ -5299,12 +5938,17 @@ async def test_list_reference_images_async_use_cached_wrapped_rpc(transport: str 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) @@ -5318,8 +5962,12 @@ async def test_list_reference_images_async_use_cached_wrapped_rpc(transport: str 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, @@ -5331,13 +5979,15 @@ async def test_list_reference_images_async(transport: str = 'grpc_asyncio', requ # 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. @@ -5349,13 +5999,14 @@ async def test_list_reference_images_async(transport: str = 'grpc_asyncio', requ # 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(), @@ -5365,12 +6016,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) @@ -5382,9 +6033,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 @@ -5397,13 +6048,15 @@ 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. @@ -5414,9 +6067,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(): @@ -5426,14 +6079,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 @@ -5441,7 +6094,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 @@ -5455,9 +6108,10 @@ 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( @@ -5466,16 +6120,18 @@ 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 @@ -5483,9 +6139,10 @@ 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( @@ -5497,7 +6154,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", ) @@ -5509,8 +6166,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( @@ -5519,17 +6176,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=[ @@ -5544,9 +6201,7 @@ 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) @@ -5556,8 +6211,11 @@ 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(), @@ -5566,8 +6224,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( @@ -5576,17 +6234,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=[ @@ -5597,9 +6255,10 @@ 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( @@ -5608,8 +6267,10 @@ 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( @@ -5618,17 +6279,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=[ @@ -5638,15 +6299,18 @@ 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 @@ -5657,8 +6321,10 @@ 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( @@ -5667,17 +6333,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=[ @@ -5690,18 +6356,22 @@ 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, @@ -5713,12 +6383,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) @@ -5730,8 +6400,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(): @@ -5739,28 +6409,31 @@ 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 @@ -5775,12 +6448,18 @@ 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) @@ -5793,8 +6472,11 @@ 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: @@ -5808,12 +6490,17 @@ async def test_get_reference_image_async_use_cached_wrapped_rpc(transport: str = 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) @@ -5827,8 +6514,12 @@ async def test_get_reference_image_async_use_cached_wrapped_rpc(transport: str = 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, @@ -5840,13 +6531,15 @@ async def test_get_reference_image_async(transport: str = 'grpc_asyncio', reques # 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. @@ -5857,14 +6550,15 @@ async def test_get_reference_image_async(transport: str = 'grpc_asyncio', reques # 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(), @@ -5874,12 +6568,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) @@ -5891,9 +6585,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 @@ -5906,13 +6600,15 @@ 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. @@ -5923,9 +6619,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(): @@ -5935,14 +6631,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 @@ -5950,7 +6646,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 @@ -5964,9 +6660,10 @@ 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( @@ -5975,16 +6672,18 @@ 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 @@ -5992,9 +6691,10 @@ 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( @@ -6006,15 +6706,18 @@ 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, @@ -6026,8 +6729,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) @@ -6047,30 +6750,33 @@ 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 @@ -6085,12 +6791,19 @@ 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) @@ -6103,8 +6816,11 @@ 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: @@ -6118,12 +6834,17 @@ async def test_add_product_to_product_set_async_use_cached_wrapped_rpc(transport 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) @@ -6137,8 +6858,12 @@ async def test_add_product_to_product_set_async_use_cached_wrapped_rpc(transport 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, @@ -6150,8 +6875,8 @@ async def test_add_product_to_product_set_async(transport: str = 'grpc_asyncio', # 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) @@ -6170,6 +6895,7 @@ async def test_add_product_to_product_set_async(transport: str = 'grpc_asyncio', 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(), @@ -6179,12 +6905,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) @@ -6196,9 +6922,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 @@ -6211,12 +6937,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) @@ -6228,9 +6954,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(): @@ -6240,15 +6966,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 @@ -6256,10 +6982,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 @@ -6273,10 +6999,11 @@ 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( @@ -6285,8 +7012,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 @@ -6294,8 +7021,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 @@ -6303,12 +7030,13 @@ 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( @@ -6320,16 +7048,19 @@ 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, @@ -6341,8 +7072,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) @@ -6362,30 +7093,33 @@ 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 @@ -6400,12 +7134,19 @@ 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) @@ -6418,8 +7159,11 @@ 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: @@ -6433,12 +7177,17 @@ async def test_remove_product_from_product_set_async_use_cached_wrapped_rpc(tran 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) @@ -6452,8 +7201,12 @@ async def test_remove_product_from_product_set_async_use_cached_wrapped_rpc(tran 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, @@ -6465,8 +7218,8 @@ async def test_remove_product_from_product_set_async(transport: str = 'grpc_asyn # 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) @@ -6485,6 +7238,7 @@ async def test_remove_product_from_product_set_async(transport: str = 'grpc_asyn 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(), @@ -6494,12 +7248,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) @@ -6511,9 +7265,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 @@ -6526,12 +7280,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) @@ -6543,9 +7297,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(): @@ -6555,15 +7309,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 @@ -6571,10 +7325,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 @@ -6588,10 +7342,11 @@ 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( @@ -6600,8 +7355,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 @@ -6609,8 +7364,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 @@ -6618,12 +7373,13 @@ 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( @@ -6635,16 +7391,19 @@ 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, @@ -6656,11 +7415,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) @@ -6672,7 +7431,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(): @@ -6680,30 +7439,33 @@ 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 @@ -6718,12 +7480,19 @@ 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) @@ -6736,8 +7505,11 @@ 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: @@ -6751,12 +7523,17 @@ async def test_list_products_in_product_set_async_use_cached_wrapped_rpc(transpo 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) @@ -6770,8 +7547,12 @@ async def test_list_products_in_product_set_async_use_cached_wrapped_rpc(transpo 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, @@ -6783,12 +7564,14 @@ async def test_list_products_in_product_set_async(transport: str = 'grpc_asyncio # 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. @@ -6799,13 +7582,14 @@ async def test_list_products_in_product_set_async(transport: str = 'grpc_asyncio # 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(), @@ -6815,12 +7599,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) @@ -6832,9 +7616,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 @@ -6847,13 +7631,15 @@ 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. @@ -6864,9 +7650,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(): @@ -6876,14 +7662,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 @@ -6891,7 +7677,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 @@ -6905,9 +7691,10 @@ 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( @@ -6916,16 +7703,18 @@ 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 @@ -6933,9 +7722,10 @@ 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( @@ -6947,7 +7737,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", ) @@ -6959,8 +7749,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( @@ -6969,17 +7759,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=[ @@ -6994,11 +7784,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', ''), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", ""),)), + ) + pager = client.list_products_in_product_set( + request={}, retry=retry, timeout=timeout ) - pager = client.list_products_in_product_set(request={}, retry=retry, timeout=timeout) assert pager._metadata == expected_metadata assert pager._retry == retry @@ -7006,8 +7796,9 @@ 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(), @@ -7016,8 +7807,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( @@ -7026,17 +7817,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=[ @@ -7047,9 +7838,10 @@ 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( @@ -7058,8 +7850,10 @@ 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( @@ -7068,17 +7862,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=[ @@ -7088,15 +7882,16 @@ 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 @@ -7107,8 +7902,10 @@ 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( @@ -7117,17 +7914,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=[ @@ -7140,18 +7937,22 @@ 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, @@ -7163,10 +7964,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. @@ -7184,28 +7985,31 @@ 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 @@ -7220,12 +8024,18 @@ 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) @@ -7243,8 +8053,11 @@ 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: @@ -7258,12 +8071,17 @@ async def test_import_product_sets_async_use_cached_wrapped_rpc(transport: str = 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) @@ -7282,8 +8100,12 @@ async def test_import_product_sets_async_use_cached_wrapped_rpc(transport: str = 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, @@ -7295,11 +8117,11 @@ async def test_import_product_sets_async(transport: str = 'grpc_asyncio', reques # 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) @@ -7317,6 +8139,7 @@ async def test_import_product_sets_async(transport: str = 'grpc_asyncio', reques 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(), @@ -7326,13 +8149,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. @@ -7343,9 +8166,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 @@ -7358,13 +8181,15 @@ 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. @@ -7375,9 +8200,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(): @@ -7387,15 +8212,19 @@ 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 @@ -7403,10 +8232,14 @@ 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 @@ -7420,10 +8253,15 @@ 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( @@ -7432,19 +8270,23 @@ 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 @@ -7452,12 +8294,17 @@ 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( @@ -7469,16 +8316,23 @@ 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, @@ -7489,11 +8343,9 @@ 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. @@ -7511,28 +8363,29 @@ 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 @@ -7551,7 +8404,9 @@ 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) @@ -7570,8 +8425,11 @@ 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: @@ -7585,12 +8443,17 @@ async def test_purge_products_async_use_cached_wrapped_rpc(transport: str = "grp 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) @@ -7609,8 +8472,12 @@ async def test_purge_products_async_use_cached_wrapped_rpc(transport: str = "grp 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, @@ -7621,12 +8488,10 @@ async def test_purge_products_async(transport: str = 'grpc_asyncio', request_typ 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) @@ -7644,6 +8509,7 @@ async def test_purge_products_async(transport: str = 'grpc_asyncio', request_typ 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(), @@ -7653,13 +8519,11 @@ 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. @@ -7670,9 +8534,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 @@ -7685,13 +8549,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. @@ -7702,9 +8566,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(): @@ -7713,15 +8577,13 @@ 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 @@ -7729,7 +8591,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 @@ -7743,9 +8605,10 @@ 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( @@ -7753,19 +8616,17 @@ 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 @@ -7773,9 +8634,10 @@ 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( @@ -7787,7 +8649,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", ) @@ -7805,12 +8667,18 @@ 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) @@ -7825,59 +8693,64 @@ 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() @@ -7887,24 +8760,32 @@ def test_create_product_set_rest_required_fields(request_type=product_search_ser 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(): @@ -7914,18 +8795,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) @@ -7935,7 +8816,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"} @@ -7945,10 +8826,14 @@ 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, @@ -7959,9 +8844,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", ) @@ -7983,8 +8868,12 @@ 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) @@ -7999,57 +8888,67 @@ 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 @@ -8057,27 +8956,37 @@ def test_list_product_sets_rest_required_fields(request_type=product_search_serv 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(): @@ -8087,16 +8996,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) @@ -8106,7 +9015,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"} @@ -8116,10 +9025,14 @@ 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, @@ -8130,20 +9043,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( @@ -8152,17 +9065,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=[ @@ -8175,24 +9088,25 @@ 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 @@ -8214,7 +9128,9 @@ 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 = {} @@ -8230,55 +9146,60 @@ 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 @@ -8289,24 +9210,24 @@ def test_get_product_set_rest_required_fields(request_type=product_search_servic 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(): @@ -8316,16 +9237,18 @@ 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) @@ -8335,7 +9258,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"} @@ -8345,10 +9268,14 @@ 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, @@ -8359,7 +9286,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", ) @@ -8377,12 +9304,18 @@ 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) @@ -8397,54 +9330,59 @@ 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() @@ -8454,24 +9392,24 @@ def test_update_product_set_rest_required_fields(request_type=product_search_ser 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(): @@ -8481,17 +9419,21 @@ 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) @@ -8501,7 +9443,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"} @@ -8511,10 +9453,14 @@ 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, @@ -8525,8 +9471,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"]), ) @@ -8544,12 +9490,18 @@ 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) @@ -8564,80 +9516,85 @@ 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(): @@ -8647,24 +9604,26 @@ 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"} @@ -8674,10 +9633,14 @@ 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, @@ -8688,7 +9651,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", ) @@ -8710,7 +9673,9 @@ 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 = {} @@ -8726,59 +9691,64 @@ 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() @@ -8788,24 +9758,32 @@ def test_create_product_rest_required_fields(request_type=product_search_service 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(): @@ -8815,18 +9793,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) @@ -8836,7 +9814,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"} @@ -8846,10 +9824,13 @@ 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, @@ -8860,9 +9841,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", ) @@ -8884,7 +9865,9 @@ 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 = {} @@ -8900,57 +9883,67 @@ 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 @@ -8961,24 +9954,32 @@ def test_list_products_rest_required_fields(request_type=product_search_service. 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(): @@ -8988,16 +9989,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) @@ -9007,7 +10008,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"} @@ -9017,10 +10018,13 @@ 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, @@ -9031,20 +10035,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( @@ -9053,17 +10057,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=[ @@ -9076,24 +10080,25 @@ 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 @@ -9115,7 +10120,9 @@ 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 = {} @@ -9131,55 +10138,60 @@ 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 @@ -9190,24 +10202,24 @@ def test_get_product_rest_required_fields(request_type=product_search_service.Ge 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(): @@ -9217,16 +10229,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) @@ -9236,7 +10248,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"} @@ -9246,10 +10258,13 @@ 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, @@ -9260,7 +10275,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", ) @@ -9282,7 +10297,9 @@ 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 = {} @@ -9298,54 +10315,59 @@ 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() @@ -9355,24 +10377,24 @@ def test_update_product_rest_required_fields(request_type=product_search_service 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(): @@ -9382,17 +10404,19 @@ 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) @@ -9402,7 +10426,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"} @@ -9412,10 +10436,14 @@ 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, @@ -9426,8 +10454,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"]), ) @@ -9449,7 +10477,9 @@ 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 = {} @@ -9465,80 +10495,85 @@ 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(): @@ -9548,24 +10583,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"} @@ -9575,10 +10610,13 @@ 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, @@ -9589,7 +10627,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", ) @@ -9607,12 +10645,19 @@ 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) @@ -9627,59 +10672,64 @@ 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() @@ -9689,24 +10739,32 @@ def test_create_reference_image_rest_required_fields(request_type=product_search 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(): @@ -9716,18 +10774,20 @@ 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) @@ -9737,7 +10797,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"} @@ -9747,10 +10807,14 @@ 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, @@ -9761,9 +10825,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", ) @@ -9781,12 +10845,19 @@ 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) @@ -9801,80 +10872,85 @@ 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(): @@ -9884,24 +10960,26 @@ 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"} @@ -9911,10 +10989,14 @@ 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, @@ -9925,7 +11007,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", ) @@ -9943,12 +11025,19 @@ 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) @@ -9963,57 +11052,67 @@ 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 @@ -10021,27 +11120,37 @@ def test_list_reference_images_rest_required_fields(request_type=product_search_ 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(): @@ -10051,16 +11160,18 @@ 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) @@ -10068,9 +11179,11 @@ 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"} @@ -10080,10 +11193,14 @@ 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, @@ -10094,20 +11211,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( @@ -10116,17 +11233,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=[ @@ -10139,24 +11256,30 @@ 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 @@ -10174,12 +11297,18 @@ 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) @@ -10194,55 +11323,60 @@ 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 @@ -10253,24 +11387,24 @@ def test_get_reference_image_rest_required_fields(request_type=product_search_se 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(): @@ -10280,16 +11414,18 @@ 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) @@ -10299,7 +11435,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"} @@ -10309,10 +11445,14 @@ 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, @@ -10323,7 +11463,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", ) @@ -10341,12 +11481,19 @@ 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) @@ -10361,7 +11508,9 @@ 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 = {} @@ -10369,77 +11518,88 @@ def test_add_product_to_product_set_rest_required_fields(request_type=product_se 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(): @@ -10449,25 +11609,27 @@ 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"} @@ -10477,10 +11639,14 @@ 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, @@ -10491,8 +11657,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", ) @@ -10510,12 +11676,19 @@ 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) @@ -10530,7 +11703,9 @@ 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 = {} @@ -10538,77 +11713,90 @@ def test_remove_product_from_product_set_rest_required_fields(request_type=produ 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(): @@ -10618,25 +11806,27 @@ 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"} @@ -10646,10 +11836,14 @@ 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, @@ -10660,8 +11854,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", ) @@ -10679,12 +11873,19 @@ 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) @@ -10699,57 +11900,67 @@ 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 @@ -10757,27 +11968,37 @@ def test_list_products_in_product_set_rest_required_fields(request_type=product_ 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(): @@ -10787,16 +12008,18 @@ 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) @@ -10804,9 +12027,11 @@ 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"} @@ -10816,10 +12041,14 @@ 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, @@ -10830,20 +12059,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( @@ -10852,17 +12081,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=[ @@ -10875,24 +12104,28 @@ 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 @@ -10910,12 +12143,18 @@ 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) @@ -10934,81 +12173,94 @@ 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(): @@ -11018,17 +12270,21 @@ 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) @@ -11036,7 +12292,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"} @@ -11046,10 +12302,14 @@ 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, @@ -11060,8 +12320,12 @@ 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" + ) + ), ) @@ -11083,7 +12347,9 @@ 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 = {} @@ -11103,81 +12369,86 @@ 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(): @@ -11187,16 +12458,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) @@ -11204,7 +12475,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"} @@ -11214,10 +12485,14 @@ 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, @@ -11228,7 +12503,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", ) @@ -11270,8 +12545,7 @@ 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. @@ -11293,6 +12567,7 @@ 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( @@ -11307,18 +12582,23 @@ 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() @@ -11328,8 +12608,7 @@ 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 @@ -11344,8 +12623,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) @@ -11367,8 +12646,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) @@ -11389,9 +12668,7 @@ 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) @@ -11413,8 +12690,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) @@ -11436,8 +12713,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) @@ -11458,9 +12735,7 @@ 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) @@ -11481,9 +12756,7 @@ 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) @@ -11504,9 +12777,7 @@ 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) @@ -11527,9 +12798,7 @@ 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) @@ -11550,9 +12819,7 @@ 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) @@ -11574,8 +12841,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) @@ -11597,8 +12864,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) @@ -11620,8 +12887,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) @@ -11643,8 +12910,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) @@ -11666,8 +12933,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) @@ -11689,8 +12956,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) @@ -11712,8 +12979,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) @@ -11735,9 +13002,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. @@ -11757,10 +13024,8 @@ 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. @@ -11780,8 +13045,7 @@ 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 @@ -11797,13 +13061,15 @@ 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. @@ -11825,12 +13091,14 @@ 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. @@ -11851,14 +13119,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. @@ -11880,13 +13148,15 @@ 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. @@ -11908,8 +13178,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) @@ -11932,16 +13202,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. @@ -11962,13 +13232,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. @@ -11989,16 +13259,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. @@ -12019,16 +13289,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. @@ -12049,9 +13319,7 @@ 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) @@ -12075,13 +13343,15 @@ 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. @@ -12103,8 +13373,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) @@ -12128,13 +13398,15 @@ 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. @@ -12156,13 +13428,15 @@ 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. @@ -12184,8 +13458,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) @@ -12209,8 +13483,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) @@ -12234,12 +13508,14 @@ 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. @@ -12261,11 +13537,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) @@ -12287,12 +13563,10 @@ 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) @@ -12311,20 +13585,24 @@ 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() @@ -12333,25 +13611,43 @@ def test_create_product_set_rest_bad_request(request_type=product_search_service 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 @@ -12365,7 +13661,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 @@ -12379,7 +13675,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 @@ -12394,12 +13690,16 @@ 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") @@ -12412,11 +13712,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 @@ -12426,34 +13726,47 @@ 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", @@ -12464,11 +13777,13 @@ 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"), ] @@ -12476,27 +13791,37 @@ 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() @@ -12505,25 +13830,27 @@ def test_list_product_sets_rest_bad_request(request_type=product_search_service. 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 @@ -12533,33 +13860,46 @@ 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", @@ -12570,39 +13910,54 @@ 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() @@ -12611,26 +13966,28 @@ def test_get_product_set_rest_bad_request(request_type=product_search_service.Ge 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 @@ -12640,34 +13997,47 @@ 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", @@ -12678,11 +14048,13 @@ 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"), ] @@ -12690,27 +14062,41 @@ 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() @@ -12719,25 +14105,47 @@ def test_update_product_set_rest_bad_request(request_type=product_search_service 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 @@ -12751,7 +14159,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 @@ -12765,7 +14173,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 @@ -12780,12 +14188,16 @@ 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") @@ -12798,11 +14210,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 @@ -12812,34 +14224,47 @@ 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", @@ -12850,11 +14275,13 @@ 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"), ] @@ -12862,27 +14289,37 @@ 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() @@ -12891,30 +14328,32 @@ def test_delete_product_set_rest_bad_request(request_type=product_search_service 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) @@ -12927,15 +14366,23 @@ 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", @@ -12948,31 +14395,41 @@ 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() @@ -12981,19 +14438,27 @@ def test_create_product_rest_bad_request(request_type=product_search_service.Cre 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 @@ -13013,7 +14478,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 @@ -13027,7 +14492,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 @@ -13042,12 +14507,16 @@ 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") @@ -13060,13 +14529,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 @@ -13076,36 +14545,48 @@ 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", @@ -13116,11 +14597,13 @@ 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"), ] @@ -13128,27 +14611,37 @@ 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() @@ -13157,25 +14650,27 @@ def test_list_products_rest_bad_request(request_type=product_search_service.List 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 @@ -13185,33 +14680,45 @@ 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", @@ -13222,39 +14729,54 @@ 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() @@ -13263,28 +14785,30 @@ def test_get_product_rest_bad_request(request_type=product_search_service.GetPro 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 @@ -13294,36 +14818,48 @@ 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", @@ -13334,11 +14870,13 @@ 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"), ] @@ -13346,27 +14884,39 @@ 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() @@ -13375,19 +14925,29 @@ def test_update_product_rest_bad_request(request_type=product_search_service.Upd 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 @@ -13407,7 +14967,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 @@ -13421,7 +14981,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 @@ -13436,12 +14996,16 @@ 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") @@ -13454,13 +15018,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 @@ -13470,36 +15034,48 @@ 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", @@ -13510,11 +15086,13 @@ 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"), ] @@ -13522,27 +15100,37 @@ 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() @@ -13551,30 +15139,32 @@ def test_delete_product_rest_bad_request(request_type=product_search_service.Del 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) @@ -13587,15 +15177,23 @@ 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", @@ -13608,31 +15206,41 @@ 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() @@ -13641,25 +15249,38 @@ def test_create_reference_image_rest_bad_request(request_type=product_search_ser 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 @@ -13673,7 +15294,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 @@ -13687,7 +15308,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 @@ -13702,12 +15323,16 @@ 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") @@ -13720,11 +15345,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 @@ -13734,34 +15359,47 @@ 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", @@ -13772,39 +15410,56 @@ 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() @@ -13813,30 +15468,34 @@ def test_delete_reference_image_rest_bad_request(request_type=product_search_ser 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) @@ -13849,15 +15508,23 @@ 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", @@ -13870,31 +15537,41 @@ 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() @@ -13903,26 +15580,28 @@ def test_list_reference_images_rest_bad_request(request_type=product_search_serv 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 @@ -13930,9 +15609,11 @@ 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) @@ -13940,26 +15621,39 @@ 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", @@ -13970,39 +15664,56 @@ 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() @@ -14011,26 +15722,30 @@ def test_get_reference_image_rest_bad_request(request_type=product_search_servic 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 @@ -14040,34 +15755,47 @@ 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", @@ -14078,39 +15806,54 @@ 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() @@ -14119,30 +15862,32 @@ def test_add_product_to_product_set_rest_bad_request(request_type=product_search 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) @@ -14155,15 +15900,23 @@ 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", @@ -14176,31 +15929,41 @@ 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() @@ -14209,30 +15972,32 @@ def test_remove_product_from_product_set_rest_bad_request(request_type=product_s 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) @@ -14245,15 +16010,24 @@ 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", @@ -14266,31 +16040,41 @@ 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() @@ -14299,25 +16083,27 @@ def test_list_products_in_product_set_rest_bad_request(request_type=product_sear 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 @@ -14325,35 +16111,50 @@ 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", @@ -14364,39 +16165,54 @@ 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() @@ -14405,30 +16221,32 @@ def test_import_product_sets_rest_bad_request(request_type=product_search_servic 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) @@ -14441,20 +16259,33 @@ 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", @@ -14469,7 +16300,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"), ] @@ -14477,27 +16308,37 @@ 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() @@ -14506,30 +16347,32 @@ def test_purge_products_rest_bad_request(request_type=product_search_service.Pur 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) @@ -14542,20 +16385,32 @@ 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", @@ -14570,7 +16425,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"), ] @@ -14578,26 +16433,39 @@ 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() @@ -14606,20 +16474,23 @@ def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperation 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() @@ -14627,7 +16498,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"} @@ -14637,10 +16508,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 @@ -14655,8 +16526,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. @@ -14677,8 +16548,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. @@ -14698,9 +16569,7 @@ 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. @@ -14721,8 +16590,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. @@ -14743,8 +16612,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. @@ -14764,9 +16633,7 @@ 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. @@ -14786,9 +16653,7 @@ 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. @@ -14808,9 +16673,7 @@ 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. @@ -14830,9 +16693,7 @@ 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. @@ -14852,9 +16713,7 @@ 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. @@ -14875,8 +16734,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. @@ -14897,8 +16756,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. @@ -14919,8 +16778,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. @@ -14941,8 +16800,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. @@ -14963,8 +16822,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. @@ -14985,8 +16844,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. @@ -15007,8 +16866,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. @@ -15029,8 +16888,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. @@ -15050,9 +16909,7 @@ 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. @@ -15073,12 +16930,13 @@ 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( @@ -15089,18 +16947,21 @@ 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(), @@ -15109,26 +16970,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): @@ -15144,7 +17005,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): @@ -15153,26 +17014,39 @@ 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() @@ -15181,15 +17055,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, ) @@ -15204,12 +17078,15 @@ 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", ) @@ -15223,39 +17100,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( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: + 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", @@ -15263,9 +17140,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, @@ -15276,10 +17153,14 @@ 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. @@ -15288,7 +17169,7 @@ def test_product_search_grpc_transport_client_cert_source_for_mtls( 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", @@ -15309,61 +17190,77 @@ def test_product_search_grpc_transport_client_cert_source_for_mtls( 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() @@ -15432,8 +17329,10 @@ 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( @@ -15446,7 +17345,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( @@ -15461,12 +17360,20 @@ 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 @@ -15475,7 +17382,7 @@ def test_product_search_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", @@ -15505,17 +17412,23 @@ def test_product_search_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.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() @@ -15546,7 +17459,7 @@ def test_product_search_transport_channel_mtls_with_adc( def test_product_search_grpc_lro_client(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) transport = client.transport @@ -15563,7 +17476,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 @@ -15581,7 +17494,11 @@ 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 @@ -15598,11 +17515,18 @@ 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 @@ -15619,13 +17543,21 @@ 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 @@ -15642,9 +17574,12 @@ 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 @@ -15659,9 +17594,12 @@ 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 @@ -15676,9 +17614,12 @@ 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 @@ -15693,9 +17634,12 @@ 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 @@ -15710,10 +17654,14 @@ 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 @@ -15733,14 +17681,18 @@ 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(), @@ -15751,7 +17703,8 @@ 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, @@ -15770,10 +17723,13 @@ 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, @@ -15795,6 +17751,7 @@ 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(), @@ -15817,7 +17774,12 @@ 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( @@ -15842,7 +17804,11 @@ 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( @@ -15859,6 +17825,8 @@ def test_get_operation_from_dict(): } ) call.assert_called() + + @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = ProductSearchAsyncClient( @@ -15880,10 +17848,11 @@ 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() @@ -15892,10 +17861,11 @@ 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() @@ -15903,10 +17873,11 @@ 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() @@ -15914,13 +17885,12 @@ 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: @@ -15929,10 +17899,14 @@ 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 @@ -15947,7 +17921,9 @@ 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 191773d5572d..cbf94b283c70 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,4 +1,3 @@ - # -*- 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 61dd10817106..c2d2bd88b483 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,6 +14,7 @@ # limitations under the License. # import os + # try/except added for compatibility with python < 3.8 try: from unittest import mock @@ -21,45 +22,48 @@ except ImportError: # pragma: NO COVER import mock -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format import json import math +from collections.abc import AsyncIterable, Iterable + +import grpc import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule +from grpc.experimental import aio from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response from requests.sessions import Session + +from google.api_core import api_core_version 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 client_options +import google.auth +from google.api_core import ( + client_options, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) 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 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.services.image_annotator import ( + ImageAnnotatorAsyncClient, + ImageAnnotatorClient, + 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 - - CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -74,9 +78,11 @@ 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(): @@ -84,17 +90,27 @@ 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(): @@ -105,20 +121,43 @@ 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"} @@ -132,27 +171,46 @@ 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, - "auto", + "never", 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(): @@ -161,7 +219,9 @@ 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. @@ -169,7 +229,9 @@ 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 @@ -181,7 +243,9 @@ 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 @@ -193,7 +257,9 @@ 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 @@ -205,7 +271,9 @@ 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 @@ -220,83 +288,167 @@ 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) @@ -312,7 +464,8 @@ 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") @@ -325,14 +478,20 @@ 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) @@ -340,52 +499,68 @@ 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" ) @@ -401,30 +576,45 @@ 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( @@ -442,13 +632,15 @@ def test_image_annotator_client_client_options(client_class, transport_class, tr # 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, @@ -460,7 +652,7 @@ def test_image_annotator_client_client_options(client_class, transport_class, tr # 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( @@ -480,17 +672,22 @@ def test_image_annotator_client_client_options(client_class, transport_class, tr 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", @@ -499,48 +696,82 @@ def test_image_annotator_client_client_options(client_class, transport_class, tr 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 @@ -559,12 +790,22 @@ def test_image_annotator_client_mtls_env_auto(client_class, transport_class, tra # 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 @@ -585,15 +826,22 @@ def test_image_annotator_client_mtls_env_auto(client_class, transport_class, tra ) # 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, @@ -603,19 +851,31 @@ def test_image_annotator_client_mtls_env_auto(client_class, transport_class, tra ) -@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 @@ -623,18 +883,25 @@ 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 @@ -671,23 +938,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 = [ @@ -718,23 +985,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"}): @@ -750,16 +1017,27 @@ 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 @@ -769,27 +1047,50 @@ 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", @@ -812,11 +1113,19 @@ 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. @@ -824,27 +1133,40 @@ 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, @@ -853,24 +1175,40 @@ def test_image_annotator_client_client_options_scopes(client_class, transport_cl 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, @@ -879,11 +1217,14 @@ def test_image_annotator_client_client_options_credentials_file(client_class, tr 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, @@ -898,23 +1239,38 @@ 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, @@ -924,13 +1280,13 @@ def test_image_annotator_client_create_channel_credentials_file(client_class, tr ) # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object(grpc_helpers, "create_channel") as create_channel, + ): creds = ga_credentials.AnonymousCredentials() file_creds = ga_credentials.AnonymousCredentials() load_creds.return_value = (file_creds, None) @@ -942,9 +1298,9 @@ def test_image_annotator_client_create_channel_credentials_file(client_class, tr 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, @@ -955,11 +1311,14 @@ def test_image_annotator_client_create_channel_credentials_file(client_class, tr ) -@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, @@ -971,11 +1330,10 @@ 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. @@ -993,25 +1351,26 @@ 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, @@ -1027,12 +1386,19 @@ 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) @@ -1045,8 +1411,11 @@ 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: @@ -1060,12 +1429,17 @@ async def test_batch_annotate_images_async_use_cached_wrapped_rpc(transport: str 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) @@ -1079,8 +1453,12 @@ async def test_batch_annotate_images_async_use_cached_wrapped_rpc(transport: str 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, @@ -1092,11 +1470,12 @@ async def test_batch_annotate_images_async(transport: str = 'grpc_asyncio', requ # 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. @@ -1121,14 +1500,18 @@ 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 @@ -1136,7 +1519,11 @@ 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 @@ -1150,9 +1537,14 @@ 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( @@ -1161,16 +1553,22 @@ 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 @@ -1178,9 +1576,14 @@ 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( @@ -1192,7 +1595,11 @@ 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") + ) + ], ) @@ -1210,12 +1617,19 @@ 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) @@ -1230,52 +1644,57 @@ 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() @@ -1285,24 +1704,24 @@ def test_batch_annotate_images_rest_required_fields(request_type=image_annotator 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(): @@ -1312,7 +1731,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() @@ -1321,7 +1740,11 @@ 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) @@ -1331,7 +1754,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"} @@ -1341,10 +1764,12 @@ 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, @@ -1355,7 +1780,11 @@ 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") + ) + ], ) @@ -1397,8 +1826,7 @@ 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. @@ -1420,6 +1848,7 @@ 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( @@ -1434,18 +1863,23 @@ 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() @@ -1455,8 +1889,7 @@ 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 @@ -1471,8 +1904,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) @@ -1493,8 +1926,7 @@ 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 @@ -1510,11 +1942,12 @@ 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. @@ -1532,20 +1965,24 @@ 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() @@ -1554,14 +1991,16 @@ def test_batch_annotate_images_rest_bad_request(request_type=image_annotator.Bat 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 @@ -1569,10 +2008,9 @@ 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() @@ -1581,7 +2019,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) @@ -1594,19 +2032,32 @@ 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", @@ -1617,28 +2068,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_initialize_client_w_rest(): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None @@ -1653,8 +2115,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. @@ -1675,18 +2137,21 @@ 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(), @@ -1694,9 +2159,7 @@ 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()) @@ -1706,7 +2169,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): @@ -1715,26 +2178,39 @@ 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() @@ -1743,15 +2219,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, ) @@ -1766,12 +2242,15 @@ 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", ) @@ -1785,39 +2264,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( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: + 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", @@ -1825,9 +2304,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, @@ -1838,10 +2317,14 @@ 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. @@ -1850,7 +2333,7 @@ def test_image_annotator_grpc_transport_client_cert_source_for_mtls( 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", @@ -1871,61 +2354,77 @@ def test_image_annotator_grpc_transport_client_cert_source_for_mtls( 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() @@ -1940,8 +2439,10 @@ 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( @@ -1954,7 +2455,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( @@ -1969,12 +2470,22 @@ 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 @@ -1983,7 +2494,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", @@ -2013,17 +2524,23 @@ 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() @@ -2053,7 +2570,9 @@ def test_image_annotator_transport_channel_mtls_with_adc( 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 @@ -2068,9 +2587,12 @@ 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 @@ -2085,9 +2607,12 @@ 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 @@ -2102,9 +2627,12 @@ 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 @@ -2119,10 +2647,14 @@ 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 @@ -2142,14 +2674,18 @@ 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(), @@ -2160,10 +2696,11 @@ 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() @@ -2172,10 +2709,11 @@ 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() @@ -2183,10 +2721,11 @@ 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() @@ -2194,13 +2733,12 @@ 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: @@ -2209,10 +2747,14 @@ 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 @@ -2227,7 +2769,9 @@ 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 191773d5572d..cbf94b283c70 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,4 +1,3 @@ - # -*- 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 f6c483a6dbb6..3378b6867a3c 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,6 +15,7 @@ # import os import re + # try/except added for compatibility with python < 3.8 try: from unittest import mock @@ -22,50 +23,53 @@ except ImportError: # pragma: NO COVER import mock -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format import json import math +from collections.abc import AsyncIterable, Iterable + +import grpc import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule +from grpc.experimental import aio from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response from requests.sessions import Session + +from google.api_core import api_core_version 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 client_options +import google.auth +from google.api_core import ( + client_options, + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operation_async, # type: ignore + operations_v1, + path_template, +) 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 from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError -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.services.image_annotator import ( + ImageAnnotatorAsyncClient, + ImageAnnotatorClient, + transports, +) from google.cloud.vision_v1p2beta1.types import image_annotator -from google.longrunning import operations_pb2 # type: ignore +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 - - CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -80,9 +84,11 @@ 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(): @@ -90,17 +96,27 @@ 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(): @@ -111,20 +127,43 @@ 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"} @@ -138,27 +177,46 @@ 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, - "auto", + "never", 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(): @@ -167,7 +225,9 @@ 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. @@ -175,7 +235,9 @@ 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 @@ -187,7 +249,9 @@ 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 @@ -199,7 +263,9 @@ 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 @@ -211,7 +277,9 @@ 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 @@ -226,83 +294,167 @@ 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) @@ -318,7 +470,8 @@ 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") @@ -331,14 +484,20 @@ 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) @@ -346,52 +505,68 @@ 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" ) @@ -407,30 +582,45 @@ 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( @@ -448,13 +638,15 @@ def test_image_annotator_client_client_options(client_class, transport_class, tr # 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, @@ -466,7 +658,7 @@ def test_image_annotator_client_client_options(client_class, transport_class, tr # 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( @@ -486,17 +678,22 @@ def test_image_annotator_client_client_options(client_class, transport_class, tr 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", @@ -505,48 +702,82 @@ def test_image_annotator_client_client_options(client_class, transport_class, tr 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 @@ -565,12 +796,22 @@ def test_image_annotator_client_mtls_env_auto(client_class, transport_class, tra # 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 @@ -591,15 +832,22 @@ def test_image_annotator_client_mtls_env_auto(client_class, transport_class, tra ) # 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, @@ -609,19 +857,31 @@ def test_image_annotator_client_mtls_env_auto(client_class, transport_class, tra ) -@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 @@ -629,18 +889,25 @@ 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 @@ -677,23 +944,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 = [ @@ -724,23 +991,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"}): @@ -756,16 +1023,27 @@ 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 @@ -775,27 +1053,50 @@ 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", @@ -818,11 +1119,19 @@ 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. @@ -830,27 +1139,40 @@ 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, @@ -859,24 +1181,40 @@ def test_image_annotator_client_client_options_scopes(client_class, transport_cl 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, @@ -885,11 +1223,14 @@ def test_image_annotator_client_client_options_credentials_file(client_class, tr 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, @@ -904,23 +1245,38 @@ 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, @@ -930,13 +1286,13 @@ def test_image_annotator_client_create_channel_credentials_file(client_class, tr ) # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object(grpc_helpers, "create_channel") as create_channel, + ): creds = ga_credentials.AnonymousCredentials() file_creds = ga_credentials.AnonymousCredentials() load_creds.return_value = (file_creds, None) @@ -948,9 +1304,9 @@ def test_image_annotator_client_create_channel_credentials_file(client_class, tr 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, @@ -961,11 +1317,14 @@ def test_image_annotator_client_create_channel_credentials_file(client_class, tr ) -@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, @@ -977,11 +1336,10 @@ 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. @@ -999,25 +1357,26 @@ 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, @@ -1033,12 +1392,19 @@ 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) @@ -1051,8 +1417,11 @@ 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: @@ -1066,12 +1435,17 @@ async def test_batch_annotate_images_async_use_cached_wrapped_rpc(transport: str 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) @@ -1085,8 +1459,12 @@ async def test_batch_annotate_images_async_use_cached_wrapped_rpc(transport: str 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, @@ -1098,11 +1476,12 @@ async def test_batch_annotate_images_async(transport: str = 'grpc_asyncio', requ # 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. @@ -1127,14 +1506,18 @@ 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 @@ -1142,7 +1525,11 @@ 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 @@ -1156,9 +1543,14 @@ 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( @@ -1167,16 +1559,22 @@ 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 @@ -1184,9 +1582,14 @@ 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( @@ -1198,15 +1601,22 @@ 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, @@ -1218,10 +1628,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. @@ -1239,25 +1649,26 @@ 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, @@ -1273,12 +1684,19 @@ 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) @@ -1296,8 +1714,11 @@ 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: @@ -1311,12 +1732,17 @@ async def test_async_batch_annotate_files_async_use_cached_wrapped_rpc(transport 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) @@ -1335,8 +1761,12 @@ async def test_async_batch_annotate_files_async_use_cached_wrapped_rpc(transport 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, @@ -1348,11 +1778,11 @@ async def test_async_batch_annotate_files_async(transport: str = 'grpc_asyncio', # 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) @@ -1378,14 +1808,20 @@ 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 @@ -1393,7 +1829,13 @@ 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 @@ -1407,9 +1849,16 @@ 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( @@ -1418,18 +1867,24 @@ 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 @@ -1437,9 +1892,16 @@ 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( @@ -1451,7 +1913,13 @@ 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") + ) + ) + ], ) @@ -1469,12 +1937,19 @@ 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) @@ -1489,52 +1964,57 @@ 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() @@ -1544,24 +2024,24 @@ def test_batch_annotate_images_rest_required_fields(request_type=image_annotator 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(): @@ -1571,7 +2051,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() @@ -1580,7 +2060,11 @@ 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) @@ -1590,7 +2074,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"} @@ -1600,10 +2084,12 @@ 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, @@ -1614,7 +2100,11 @@ 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") + ) + ], ) @@ -1632,12 +2122,19 @@ 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) @@ -1656,76 +2153,81 @@ 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(): @@ -1735,16 +2237,22 @@ 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) @@ -1752,7 +2260,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"} @@ -1762,10 +2270,12 @@ 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, @@ -1776,7 +2286,13 @@ 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") + ) + ) + ], ) @@ -1818,8 +2334,7 @@ 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. @@ -1841,6 +2356,7 @@ 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( @@ -1855,18 +2371,23 @@ 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() @@ -1876,8 +2397,7 @@ 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 @@ -1892,8 +2412,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) @@ -1915,9 +2435,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. @@ -1937,8 +2457,7 @@ 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 @@ -1954,11 +2473,12 @@ 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. @@ -1980,11 +2500,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) @@ -2003,20 +2523,24 @@ 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() @@ -2025,14 +2549,16 @@ def test_batch_annotate_images_rest_bad_request(request_type=image_annotator.Bat 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 @@ -2040,10 +2566,9 @@ 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() @@ -2052,7 +2577,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) @@ -2065,19 +2590,32 @@ 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", @@ -2088,39 +2626,54 @@ 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() @@ -2129,14 +2682,16 @@ def test_async_batch_annotate_files_rest_bad_request(request_type=image_annotato 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 @@ -2144,15 +2699,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) @@ -2165,20 +2720,33 @@ 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", @@ -2193,7 +2761,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"), ] @@ -2201,16 +2769,22 @@ 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 @@ -2225,8 +2799,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. @@ -2247,8 +2821,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. @@ -2269,12 +2843,13 @@ 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( @@ -2285,18 +2860,21 @@ 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(), @@ -2305,8 +2883,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): @@ -2322,7 +2900,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): @@ -2331,26 +2909,39 @@ 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() @@ -2359,15 +2950,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, ) @@ -2382,12 +2973,15 @@ 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", ) @@ -2401,39 +2995,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( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: + 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", @@ -2441,9 +3035,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, @@ -2454,10 +3048,14 @@ 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. @@ -2466,7 +3064,7 @@ def test_image_annotator_grpc_transport_client_cert_source_for_mtls( 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", @@ -2487,61 +3085,77 @@ def test_image_annotator_grpc_transport_client_cert_source_for_mtls( 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() @@ -2559,8 +3173,10 @@ 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( @@ -2573,7 +3189,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( @@ -2588,12 +3204,22 @@ 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 @@ -2602,7 +3228,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", @@ -2632,17 +3258,23 @@ 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() @@ -2673,7 +3305,7 @@ def test_image_annotator_transport_channel_mtls_with_adc( def test_image_annotator_grpc_lro_client(): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) transport = client.transport @@ -2690,7 +3322,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 @@ -2706,7 +3338,9 @@ 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 @@ -2721,9 +3355,12 @@ 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 @@ -2738,9 +3375,12 @@ 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 @@ -2755,9 +3395,12 @@ 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 @@ -2772,10 +3415,14 @@ 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 @@ -2795,14 +3442,18 @@ 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(), @@ -2813,10 +3464,11 @@ 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() @@ -2825,10 +3477,11 @@ 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() @@ -2836,10 +3489,11 @@ 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() @@ -2847,13 +3501,12 @@ 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: @@ -2862,10 +3515,14 @@ 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 @@ -2880,7 +3537,9 @@ 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 191773d5572d..cbf94b283c70 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,4 +1,3 @@ - # -*- 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 eb8fba26dcae..3ee75983a5fc 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,6 +14,7 @@ # limitations under the License. # import os + # try/except added for compatibility with python < 3.8 try: from unittest import mock @@ -21,52 +22,57 @@ except ImportError: # pragma: NO COVER import mock -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format import json import math +from collections.abc import AsyncIterable, Iterable + +import grpc import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule +from grpc.experimental import aio from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response from requests.sessions import Session + +from google.api_core import api_core_version 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 client_options +import google.auth +from google.api_core import ( + client_options, + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operation_async, # type: ignore + operations_v1, + path_template, +) 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 from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError -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.cloud.vision_v1p3beta1.services.image_annotator import ( + ImageAnnotatorAsyncClient, + ImageAnnotatorClient, + transports, +) +from google.cloud.vision_v1p3beta1.types import ( + geometry, + image_annotator, + 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 - - CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -81,9 +87,11 @@ 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(): @@ -91,17 +99,27 @@ 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(): @@ -112,20 +130,43 @@ 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"} @@ -139,27 +180,46 @@ 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, - "auto", + "never", 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(): @@ -168,7 +228,9 @@ 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. @@ -176,7 +238,9 @@ 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 @@ -188,7 +252,9 @@ 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 @@ -200,7 +266,9 @@ 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 @@ -212,7 +280,9 @@ 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 @@ -227,83 +297,167 @@ 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) @@ -319,7 +473,8 @@ 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") @@ -332,14 +487,20 @@ 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) @@ -347,52 +508,68 @@ 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" ) @@ -408,30 +585,45 @@ 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( @@ -449,13 +641,15 @@ def test_image_annotator_client_client_options(client_class, transport_class, tr # 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, @@ -467,7 +661,7 @@ def test_image_annotator_client_client_options(client_class, transport_class, tr # 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( @@ -487,17 +681,22 @@ def test_image_annotator_client_client_options(client_class, transport_class, tr 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", @@ -506,48 +705,82 @@ def test_image_annotator_client_client_options(client_class, transport_class, tr 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 @@ -566,12 +799,22 @@ def test_image_annotator_client_mtls_env_auto(client_class, transport_class, tra # 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 @@ -592,15 +835,22 @@ def test_image_annotator_client_mtls_env_auto(client_class, transport_class, tra ) # 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, @@ -610,19 +860,31 @@ def test_image_annotator_client_mtls_env_auto(client_class, transport_class, tra ) -@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 @@ -630,18 +892,25 @@ 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 @@ -678,23 +947,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 = [ @@ -725,23 +994,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"}): @@ -757,16 +1026,27 @@ 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 @@ -776,27 +1056,50 @@ 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", @@ -819,11 +1122,19 @@ 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. @@ -831,27 +1142,40 @@ 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, @@ -860,24 +1184,40 @@ def test_image_annotator_client_client_options_scopes(client_class, transport_cl 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, @@ -886,11 +1226,14 @@ def test_image_annotator_client_client_options_credentials_file(client_class, tr 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, @@ -905,23 +1248,38 @@ 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, @@ -931,13 +1289,13 @@ def test_image_annotator_client_create_channel_credentials_file(client_class, tr ) # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object(grpc_helpers, "create_channel") as create_channel, + ): creds = ga_credentials.AnonymousCredentials() file_creds = ga_credentials.AnonymousCredentials() load_creds.return_value = (file_creds, None) @@ -949,9 +1307,9 @@ def test_image_annotator_client_create_channel_credentials_file(client_class, tr 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, @@ -962,11 +1320,14 @@ def test_image_annotator_client_create_channel_credentials_file(client_class, tr ) -@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, @@ -978,11 +1339,10 @@ 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. @@ -1000,25 +1360,26 @@ 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, @@ -1034,12 +1395,19 @@ 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) @@ -1052,8 +1420,11 @@ 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: @@ -1067,12 +1438,17 @@ async def test_batch_annotate_images_async_use_cached_wrapped_rpc(transport: str 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) @@ -1086,8 +1462,12 @@ async def test_batch_annotate_images_async_use_cached_wrapped_rpc(transport: str 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, @@ -1099,11 +1479,12 @@ async def test_batch_annotate_images_async(transport: str = 'grpc_asyncio', requ # 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. @@ -1128,14 +1509,18 @@ 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 @@ -1143,7 +1528,11 @@ 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 @@ -1157,9 +1546,14 @@ 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( @@ -1168,16 +1562,22 @@ 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 @@ -1185,9 +1585,14 @@ 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( @@ -1199,15 +1604,22 @@ 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, @@ -1219,10 +1631,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. @@ -1240,25 +1652,26 @@ 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, @@ -1274,12 +1687,19 @@ 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) @@ -1297,8 +1717,11 @@ 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: @@ -1312,12 +1735,17 @@ async def test_async_batch_annotate_files_async_use_cached_wrapped_rpc(transport 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) @@ -1336,8 +1764,12 @@ async def test_async_batch_annotate_files_async_use_cached_wrapped_rpc(transport 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, @@ -1349,11 +1781,11 @@ async def test_async_batch_annotate_files_async(transport: str = 'grpc_asyncio', # 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) @@ -1379,14 +1811,20 @@ 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 @@ -1394,7 +1832,13 @@ 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 @@ -1408,9 +1852,16 @@ 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( @@ -1419,18 +1870,24 @@ 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 @@ -1438,9 +1895,16 @@ 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( @@ -1452,7 +1916,13 @@ 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") + ) + ) + ], ) @@ -1470,12 +1940,19 @@ 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) @@ -1490,52 +1967,57 @@ 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() @@ -1545,24 +2027,24 @@ def test_batch_annotate_images_rest_required_fields(request_type=image_annotator 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(): @@ -1572,7 +2054,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() @@ -1581,7 +2063,11 @@ 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) @@ -1591,7 +2077,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"} @@ -1601,10 +2087,12 @@ 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, @@ -1615,7 +2103,11 @@ 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") + ) + ], ) @@ -1633,12 +2125,19 @@ 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) @@ -1657,76 +2156,81 @@ 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(): @@ -1736,16 +2240,22 @@ 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) @@ -1753,7 +2263,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"} @@ -1763,10 +2273,12 @@ 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, @@ -1777,7 +2289,13 @@ 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") + ) + ) + ], ) @@ -1819,8 +2337,7 @@ 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. @@ -1842,6 +2359,7 @@ 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( @@ -1856,18 +2374,23 @@ 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() @@ -1877,8 +2400,7 @@ 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 @@ -1893,8 +2415,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) @@ -1916,9 +2438,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. @@ -1938,8 +2460,7 @@ 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 @@ -1955,11 +2476,12 @@ 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. @@ -1981,11 +2503,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) @@ -2004,20 +2526,24 @@ 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() @@ -2026,14 +2552,16 @@ def test_batch_annotate_images_rest_bad_request(request_type=image_annotator.Bat 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 @@ -2041,10 +2569,9 @@ 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() @@ -2053,7 +2580,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) @@ -2066,19 +2593,32 @@ 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", @@ -2089,39 +2629,54 @@ 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() @@ -2130,14 +2685,16 @@ def test_async_batch_annotate_files_rest_bad_request(request_type=image_annotato 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 @@ -2145,15 +2702,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) @@ -2166,20 +2723,33 @@ 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", @@ -2194,7 +2764,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"), ] @@ -2202,16 +2772,22 @@ 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 @@ -2226,8 +2802,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. @@ -2248,8 +2824,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. @@ -2270,12 +2846,13 @@ 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( @@ -2286,18 +2863,21 @@ 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(), @@ -2306,8 +2886,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): @@ -2323,7 +2903,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): @@ -2332,26 +2912,39 @@ 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() @@ -2360,15 +2953,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, ) @@ -2383,12 +2976,15 @@ 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", ) @@ -2402,39 +2998,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( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: + 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", @@ -2442,9 +3038,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, @@ -2455,10 +3051,14 @@ 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. @@ -2467,7 +3067,7 @@ def test_image_annotator_grpc_transport_client_cert_source_for_mtls( 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", @@ -2488,61 +3088,77 @@ def test_image_annotator_grpc_transport_client_cert_source_for_mtls( 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() @@ -2560,8 +3176,10 @@ 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( @@ -2574,7 +3192,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( @@ -2589,12 +3207,22 @@ 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 @@ -2603,7 +3231,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", @@ -2633,17 +3261,23 @@ 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() @@ -2674,7 +3308,7 @@ def test_image_annotator_transport_channel_mtls_with_adc( def test_image_annotator_grpc_lro_client(): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) transport = client.transport @@ -2691,7 +3325,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 @@ -2709,7 +3343,11 @@ 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 @@ -2726,11 +3364,18 @@ 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 @@ -2747,9 +3392,12 @@ 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 @@ -2764,9 +3412,12 @@ 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 @@ -2781,9 +3432,12 @@ 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 @@ -2798,9 +3452,12 @@ 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 @@ -2815,10 +3472,14 @@ 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 @@ -2838,14 +3499,18 @@ 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(), @@ -2856,10 +3521,11 @@ 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() @@ -2868,10 +3534,11 @@ 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() @@ -2879,10 +3546,11 @@ 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() @@ -2890,13 +3558,12 @@ 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: @@ -2905,10 +3572,14 @@ 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 @@ -2923,7 +3594,9 @@ 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 2a23346a0f07..ceb825065a7e 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,6 +14,7 @@ # limitations under the License. # import os + # try/except added for compatibility with python < 3.8 try: from unittest import mock @@ -21,55 +22,59 @@ except ImportError: # pragma: NO COVER import mock -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format import json import math +from collections.abc import AsyncIterable, Iterable + +import grpc import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule +from grpc.experimental import aio from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response from requests.sessions import Session + +from google.api_core import api_core_version 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 client_options +import google.auth +from google.api_core import ( + client_options, + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operation_async, # type: ignore + operations_v1, + path_template, +) 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 from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError -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.cloud.vision_v1p3beta1.services.product_search import ( + ProductSearchAsyncClient, + ProductSearchClient, + pagers, + transports, +) +from google.cloud.vision_v1p3beta1.types import geometry, 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.protobuf import ( + any_pb2, # type: ignore + field_mask_pb2, # type: ignore + timestamp_pb2, # type: ignore +) from google.rpc import status_pb2 # type: ignore -import google.auth - - CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -84,9 +89,11 @@ 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(): @@ -94,17 +101,27 @@ 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(): @@ -115,11 +132,26 @@ 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) @@ -128,7 +160,11 @@ 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"} @@ -142,27 +178,46 @@ 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, - "auto", + "never", 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(): @@ -171,7 +226,9 @@ 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. @@ -179,7 +236,9 @@ 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 @@ -191,7 +250,9 @@ 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 @@ -203,7 +264,9 @@ 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 @@ -215,7 +278,9 @@ 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 @@ -230,83 +295,167 @@ 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) @@ -322,7 +471,8 @@ 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") @@ -335,14 +485,20 @@ 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) @@ -350,52 +506,68 @@ 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" ) @@ -411,30 +583,45 @@ 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( @@ -452,13 +639,15 @@ def test_product_search_client_client_options(client_class, transport_class, tra # 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, @@ -470,7 +659,7 @@ def test_product_search_client_client_options(client_class, transport_class, tra # 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( @@ -490,17 +679,22 @@ def test_product_search_client_client_options(client_class, transport_class, tra 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", @@ -509,48 +703,82 @@ def test_product_search_client_client_options(client_class, transport_class, tra 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 @@ -569,12 +797,22 @@ def test_product_search_client_mtls_env_auto(client_class, transport_class, tran # 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 @@ -595,15 +833,22 @@ def test_product_search_client_mtls_env_auto(client_class, transport_class, tran ) # 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, @@ -613,19 +858,31 @@ def test_product_search_client_mtls_env_auto(client_class, transport_class, tran ) -@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 @@ -633,18 +890,25 @@ 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 @@ -681,23 +945,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 = [ @@ -728,23 +992,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"}): @@ -760,16 +1024,27 @@ 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 @@ -779,27 +1054,50 @@ 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", @@ -822,11 +1120,19 @@ 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. @@ -834,27 +1140,40 @@ 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, @@ -863,24 +1182,40 @@ def test_product_search_client_client_options_scopes(client_class, transport_cla 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, @@ -889,11 +1224,14 @@ def test_product_search_client_client_options_credentials_file(client_class, tra 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, @@ -908,23 +1246,38 @@ 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, @@ -934,13 +1287,13 @@ def test_product_search_client_create_channel_credentials_file(client_class, tra ) # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object(grpc_helpers, "create_channel") as create_channel, + ): creds = ga_credentials.AnonymousCredentials() file_creds = ga_credentials.AnonymousCredentials() load_creds.return_value = (file_creds, None) @@ -952,9 +1305,9 @@ def test_product_search_client_create_channel_credentials_file(client_class, tra 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, @@ -965,11 +1318,14 @@ def test_product_search_client_create_channel_credentials_file(client_class, tra ) -@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, @@ -981,12 +1337,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) @@ -998,8 +1354,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(): @@ -1007,30 +1363,33 @@ 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 @@ -1045,12 +1404,18 @@ 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) @@ -1063,8 +1428,11 @@ 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: @@ -1078,12 +1446,17 @@ async def test_create_product_set_async_use_cached_wrapped_rpc(transport: str = 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) @@ -1097,8 +1470,12 @@ async def test_create_product_set_async_use_cached_wrapped_rpc(transport: str = 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, @@ -1110,13 +1487,15 @@ async def test_create_product_set_async(transport: str = 'grpc_asyncio', request # 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. @@ -1127,14 +1506,15 @@ async def test_create_product_set_async(transport: str = 'grpc_asyncio', 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.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(), @@ -1144,12 +1524,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) @@ -1161,9 +1541,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 @@ -1176,13 +1556,15 @@ 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. @@ -1193,9 +1575,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(): @@ -1205,16 +1587,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 @@ -1222,13 +1604,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 @@ -1242,11 +1624,12 @@ 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( @@ -1255,18 +1638,20 @@ 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 @@ -1274,15 +1659,16 @@ 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( @@ -1294,17 +1680,20 @@ 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, @@ -1316,11 +1705,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) @@ -1332,7 +1721,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(): @@ -1340,30 +1729,33 @@ 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 @@ -1382,8 +1774,12 @@ 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) @@ -1396,8 +1792,11 @@ 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: @@ -1411,12 +1810,17 @@ async def test_list_product_sets_async_use_cached_wrapped_rpc(transport: str = " 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) @@ -1430,8 +1834,12 @@ async def test_list_product_sets_async_use_cached_wrapped_rpc(transport: str = " 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, @@ -1443,12 +1851,14 @@ async def test_list_product_sets_async(transport: str = 'grpc_asyncio', request_ # 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. @@ -1459,13 +1869,14 @@ async def test_list_product_sets_async(transport: str = 'grpc_asyncio', request_ # 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(), @@ -1475,12 +1886,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) @@ -1492,9 +1903,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 @@ -1507,13 +1918,15 @@ 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. @@ -1524,9 +1937,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(): @@ -1536,14 +1949,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 @@ -1551,7 +1964,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 @@ -1565,9 +1978,10 @@ 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( @@ -1576,16 +1990,18 @@ 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 @@ -1593,9 +2009,10 @@ 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( @@ -1607,7 +2024,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", ) @@ -1619,8 +2036,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( @@ -1629,17 +2046,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=[ @@ -1654,9 +2071,7 @@ 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) @@ -1666,8 +2081,9 @@ 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(), @@ -1676,8 +2092,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( @@ -1686,17 +2102,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=[ @@ -1707,9 +2123,10 @@ 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( @@ -1718,8 +2135,10 @@ 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( @@ -1728,17 +2147,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=[ @@ -1748,15 +2167,16 @@ 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 @@ -1767,8 +2187,10 @@ 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( @@ -1777,17 +2199,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=[ @@ -1800,18 +2222,22 @@ 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, @@ -1822,13 +2248,11 @@ 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) @@ -1840,8 +2264,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(): @@ -1849,28 +2273,29 @@ 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 @@ -1889,7 +2314,9 @@ 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) @@ -1903,8 +2330,11 @@ 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: @@ -1918,12 +2348,17 @@ async def test_get_product_set_async_use_cached_wrapped_rpc(transport: str = "gr 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) @@ -1937,8 +2372,12 @@ async def test_get_product_set_async_use_cached_wrapped_rpc(transport: str = "gr 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, @@ -1949,14 +2388,14 @@ async def test_get_product_set_async(transport: str = 'grpc_asyncio', request_ty 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. @@ -1967,14 +2406,15 @@ async def test_get_product_set_async(transport: str = 'grpc_asyncio', request_ty # 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(), @@ -1984,12 +2424,10 @@ 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) @@ -2001,9 +2439,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 @@ -2016,13 +2454,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. @@ -2033,9 +2471,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(): @@ -2044,15 +2482,13 @@ 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 @@ -2060,7 +2496,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 @@ -2074,9 +2510,10 @@ 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( @@ -2084,17 +2521,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 @@ -2102,9 +2539,10 @@ 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( @@ -2116,15 +2554,18 @@ 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, @@ -2136,12 +2577,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) @@ -2153,8 +2594,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(): @@ -2162,25 +2603,26 @@ 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, @@ -2196,12 +2638,18 @@ 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) @@ -2214,8 +2662,11 @@ 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: @@ -2229,12 +2680,17 @@ async def test_update_product_set_async_use_cached_wrapped_rpc(transport: str = 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) @@ -2248,8 +2704,12 @@ async def test_update_product_set_async_use_cached_wrapped_rpc(transport: str = 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, @@ -2261,13 +2721,15 @@ async def test_update_product_set_async(transport: str = 'grpc_asyncio', request # 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. @@ -2278,14 +2740,15 @@ async def test_update_product_set_async(transport: str = 'grpc_asyncio', 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.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(), @@ -2295,12 +2758,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) @@ -2312,9 +2775,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 @@ -2327,13 +2790,15 @@ 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. @@ -2344,9 +2809,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(): @@ -2356,15 +2821,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 @@ -2372,10 +2837,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 @@ -2389,10 +2854,11 @@ 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( @@ -2401,17 +2867,19 @@ 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 @@ -2419,12 +2887,13 @@ 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( @@ -2436,16 +2905,19 @@ 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, @@ -2457,8 +2929,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) @@ -2478,28 +2950,31 @@ 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 @@ -2514,12 +2989,18 @@ 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) @@ -2532,8 +3013,11 @@ 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: @@ -2547,12 +3031,17 @@ async def test_delete_product_set_async_use_cached_wrapped_rpc(transport: str = 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) @@ -2566,8 +3055,12 @@ async def test_delete_product_set_async_use_cached_wrapped_rpc(transport: str = 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, @@ -2579,8 +3072,8 @@ async def test_delete_product_set_async(transport: str = 'grpc_asyncio', request # 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) @@ -2599,6 +3092,7 @@ async def test_delete_product_set_async(transport: str = 'grpc_asyncio', request 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(), @@ -2608,12 +3102,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) @@ -2625,9 +3119,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 @@ -2640,12 +3134,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) @@ -2657,9 +3151,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(): @@ -2669,14 +3163,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 @@ -2684,7 +3178,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 @@ -2698,9 +3192,10 @@ 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( @@ -2709,8 +3204,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 @@ -2718,7 +3213,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 @@ -2726,9 +3221,10 @@ 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( @@ -2740,15 +3236,18 @@ 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, @@ -2759,15 +3258,13 @@ 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) @@ -2779,10 +3276,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(): @@ -2790,30 +3287,31 @@ 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 @@ -2832,7 +3330,9 @@ 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) @@ -2846,8 +3346,11 @@ 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: @@ -2861,12 +3364,17 @@ async def test_create_product_async_use_cached_wrapped_rpc(transport: str = "grp 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) @@ -2880,8 +3388,12 @@ async def test_create_product_async_use_cached_wrapped_rpc(transport: str = "grp 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, @@ -2892,16 +3404,16 @@ async def test_create_product_async(transport: str = 'grpc_asyncio', request_typ 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. @@ -2912,16 +3424,17 @@ async def test_create_product_async(transport: str = 'grpc_asyncio', request_typ # 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(), @@ -2931,12 +3444,10 @@ 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) @@ -2948,9 +3459,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 @@ -2963,13 +3474,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. @@ -2980,9 +3491,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(): @@ -2991,17 +3502,15 @@ 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 @@ -3009,13 +3518,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 @@ -3029,11 +3538,12 @@ 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( @@ -3041,19 +3551,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 @@ -3061,15 +3571,16 @@ 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( @@ -3081,17 +3592,20 @@ 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, @@ -3102,12 +3616,10 @@ 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) @@ -3119,7 +3631,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(): @@ -3127,30 +3639,31 @@ 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 @@ -3169,7 +3682,9 @@ 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) @@ -3183,8 +3698,11 @@ 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: @@ -3198,12 +3716,17 @@ async def test_list_products_async_use_cached_wrapped_rpc(transport: str = "grpc 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) @@ -3217,8 +3740,12 @@ async def test_list_products_async_use_cached_wrapped_rpc(transport: str = "grpc 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, @@ -3229,13 +3756,13 @@ async def test_list_products_async(transport: str = 'grpc_asyncio', request_type 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. @@ -3246,13 +3773,14 @@ async def test_list_products_async(transport: str = 'grpc_asyncio', request_type # 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(), @@ -3262,12 +3790,10 @@ 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) @@ -3279,9 +3805,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 @@ -3294,13 +3820,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. @@ -3311,9 +3837,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(): @@ -3322,15 +3848,13 @@ 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 @@ -3338,7 +3862,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 @@ -3352,9 +3876,10 @@ 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( @@ -3362,17 +3887,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 @@ -3380,9 +3905,10 @@ 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( @@ -3394,7 +3920,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", ) @@ -3405,9 +3931,7 @@ 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( @@ -3416,17 +3940,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=[ @@ -3441,9 +3965,7 @@ 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) @@ -3453,8 +3975,9 @@ 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(), @@ -3462,9 +3985,7 @@ 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( @@ -3473,17 +3994,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=[ @@ -3494,9 +4015,10 @@ 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( @@ -3505,8 +4027,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( @@ -3515,17 +4037,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=[ @@ -3535,15 +4057,16 @@ 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 @@ -3554,8 +4077,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( @@ -3564,17 +4087,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=[ @@ -3587,18 +4110,22 @@ 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, @@ -3609,15 +4136,13 @@ 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) @@ -3629,10 +4154,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(): @@ -3640,28 +4165,29 @@ 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 @@ -3680,7 +4206,9 @@ 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) @@ -3694,8 +4222,11 @@ 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: @@ -3709,12 +4240,17 @@ async def test_get_product_async_use_cached_wrapped_rpc(transport: str = "grpc_a 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) @@ -3728,8 +4264,12 @@ async def test_get_product_async_use_cached_wrapped_rpc(transport: str = "grpc_a 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, @@ -3740,16 +4280,16 @@ async def test_get_product_async(transport: str = 'grpc_asyncio', request_type=p 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. @@ -3760,16 +4300,17 @@ async def test_get_product_async(transport: str = 'grpc_asyncio', request_type=p # 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(), @@ -3779,12 +4320,10 @@ 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) @@ -3796,9 +4335,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 @@ -3811,13 +4350,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. @@ -3828,9 +4367,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(): @@ -3839,15 +4378,13 @@ 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 @@ -3855,7 +4392,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 @@ -3869,9 +4406,10 @@ 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( @@ -3879,17 +4417,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 @@ -3897,9 +4435,10 @@ 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( @@ -3911,15 +4450,18 @@ 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, @@ -3930,15 +4472,13 @@ 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) @@ -3950,10 +4490,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(): @@ -3961,25 +4501,24 @@ 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, @@ -3999,7 +4538,9 @@ 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) @@ -4013,8 +4554,11 @@ 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: @@ -4028,12 +4572,17 @@ async def test_update_product_async_use_cached_wrapped_rpc(transport: str = "grp 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) @@ -4047,8 +4596,12 @@ async def test_update_product_async_use_cached_wrapped_rpc(transport: str = "grp 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, @@ -4059,16 +4612,16 @@ async def test_update_product_async(transport: str = 'grpc_asyncio', request_typ 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. @@ -4079,16 +4632,17 @@ async def test_update_product_async(transport: str = 'grpc_asyncio', request_typ # 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(), @@ -4098,12 +4652,10 @@ 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) @@ -4115,9 +4667,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 @@ -4130,13 +4682,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. @@ -4147,9 +4699,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(): @@ -4158,16 +4710,14 @@ 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 @@ -4175,10 +4725,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 @@ -4192,10 +4742,11 @@ 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( @@ -4203,18 +4754,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 @@ -4222,12 +4773,13 @@ 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( @@ -4239,16 +4791,19 @@ 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, @@ -4259,9 +4814,7 @@ 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) @@ -4281,28 +4834,29 @@ 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 @@ -4321,7 +4875,9 @@ 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) @@ -4335,8 +4891,11 @@ 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: @@ -4350,12 +4909,17 @@ async def test_delete_product_async_use_cached_wrapped_rpc(transport: str = "grp 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) @@ -4369,8 +4933,12 @@ async def test_delete_product_async_use_cached_wrapped_rpc(transport: str = "grp 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, @@ -4381,9 +4949,7 @@ async def test_delete_product_async(transport: str = 'grpc_asyncio', request_typ 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) @@ -4402,6 +4968,7 @@ async def test_delete_product_async(transport: str = 'grpc_asyncio', request_typ 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(), @@ -4411,12 +4978,10 @@ 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) @@ -4428,9 +4993,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 @@ -4443,12 +5008,10 @@ 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) @@ -4460,9 +5023,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(): @@ -4471,15 +5034,13 @@ 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 @@ -4487,7 +5048,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 @@ -4501,9 +5062,10 @@ 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( @@ -4511,9 +5073,7 @@ 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 @@ -4521,7 +5081,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 @@ -4529,9 +5089,10 @@ 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( @@ -4543,15 +5104,18 @@ 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, @@ -4563,12 +5127,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) @@ -4580,8 +5144,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(): @@ -4589,30 +5153,33 @@ 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 @@ -4627,12 +5194,19 @@ 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) @@ -4645,8 +5219,11 @@ 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: @@ -4660,12 +5237,17 @@ async def test_create_reference_image_async_use_cached_wrapped_rpc(transport: st 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) @@ -4679,8 +5261,12 @@ async def test_create_reference_image_async_use_cached_wrapped_rpc(transport: st 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, @@ -4692,13 +5278,15 @@ async def test_create_reference_image_async(transport: str = 'grpc_asyncio', req # 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. @@ -4709,14 +5297,15 @@ async def test_create_reference_image_async(transport: str = 'grpc_asyncio', req # 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(), @@ -4726,12 +5315,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) @@ -4743,9 +5332,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 @@ -4758,13 +5347,15 @@ 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. @@ -4775,9 +5366,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(): @@ -4787,16 +5378,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 @@ -4804,13 +5395,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 @@ -4824,11 +5415,12 @@ 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( @@ -4837,18 +5429,20 @@ 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 @@ -4856,15 +5450,16 @@ 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( @@ -4876,17 +5471,20 @@ 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, @@ -4898,8 +5496,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) @@ -4919,28 +5517,31 @@ 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 @@ -4955,12 +5556,19 @@ 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) @@ -4973,8 +5581,11 @@ 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: @@ -4988,12 +5599,17 @@ async def test_delete_reference_image_async_use_cached_wrapped_rpc(transport: st 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) @@ -5007,8 +5623,12 @@ async def test_delete_reference_image_async_use_cached_wrapped_rpc(transport: st 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, @@ -5020,8 +5640,8 @@ async def test_delete_reference_image_async(transport: str = 'grpc_asyncio', req # 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) @@ -5040,6 +5660,7 @@ async def test_delete_reference_image_async(transport: str = 'grpc_asyncio', req 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(), @@ -5049,12 +5670,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) @@ -5066,9 +5687,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 @@ -5081,12 +5702,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) @@ -5098,9 +5719,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(): @@ -5110,14 +5731,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 @@ -5125,7 +5746,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 @@ -5139,9 +5760,10 @@ 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( @@ -5150,8 +5772,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 @@ -5159,7 +5781,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 @@ -5167,9 +5789,10 @@ 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( @@ -5181,15 +5804,18 @@ 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, @@ -5201,12 +5827,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) @@ -5219,7 +5845,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(): @@ -5227,30 +5853,33 @@ 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 @@ -5265,12 +5894,19 @@ 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) @@ -5283,8 +5919,11 @@ 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: @@ -5298,12 +5937,17 @@ async def test_list_reference_images_async_use_cached_wrapped_rpc(transport: str 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) @@ -5317,8 +5961,12 @@ async def test_list_reference_images_async_use_cached_wrapped_rpc(transport: str 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, @@ -5330,13 +5978,15 @@ async def test_list_reference_images_async(transport: str = 'grpc_asyncio', requ # 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. @@ -5348,13 +5998,14 @@ async def test_list_reference_images_async(transport: str = 'grpc_asyncio', requ # 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(), @@ -5364,12 +6015,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) @@ -5381,9 +6032,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 @@ -5396,13 +6047,15 @@ 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. @@ -5413,9 +6066,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(): @@ -5425,14 +6078,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 @@ -5440,7 +6093,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 @@ -5454,9 +6107,10 @@ 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( @@ -5465,16 +6119,18 @@ 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 @@ -5482,9 +6138,10 @@ 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( @@ -5496,7 +6153,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", ) @@ -5508,8 +6165,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( @@ -5518,17 +6175,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=[ @@ -5543,9 +6200,7 @@ 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) @@ -5555,8 +6210,11 @@ 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(), @@ -5565,8 +6223,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( @@ -5575,17 +6233,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=[ @@ -5596,9 +6254,10 @@ 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( @@ -5607,8 +6266,10 @@ 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( @@ -5617,17 +6278,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=[ @@ -5637,15 +6298,18 @@ 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 @@ -5656,8 +6320,10 @@ 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( @@ -5666,17 +6332,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=[ @@ -5689,18 +6355,22 @@ 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, @@ -5712,12 +6382,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) @@ -5729,8 +6399,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(): @@ -5738,28 +6408,31 @@ 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 @@ -5774,12 +6447,18 @@ 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) @@ -5792,8 +6471,11 @@ 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: @@ -5807,12 +6489,17 @@ async def test_get_reference_image_async_use_cached_wrapped_rpc(transport: str = 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) @@ -5826,8 +6513,12 @@ async def test_get_reference_image_async_use_cached_wrapped_rpc(transport: str = 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, @@ -5839,13 +6530,15 @@ async def test_get_reference_image_async(transport: str = 'grpc_asyncio', reques # 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. @@ -5856,14 +6549,15 @@ async def test_get_reference_image_async(transport: str = 'grpc_asyncio', reques # 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(), @@ -5873,12 +6567,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) @@ -5890,9 +6584,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 @@ -5905,13 +6599,15 @@ 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. @@ -5922,9 +6618,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(): @@ -5934,14 +6630,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 @@ -5949,7 +6645,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 @@ -5963,9 +6659,10 @@ 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( @@ -5974,16 +6671,18 @@ 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 @@ -5991,9 +6690,10 @@ 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( @@ -6005,15 +6705,18 @@ 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, @@ -6025,8 +6728,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) @@ -6046,30 +6749,33 @@ 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 @@ -6084,12 +6790,19 @@ 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) @@ -6102,8 +6815,11 @@ 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: @@ -6117,12 +6833,17 @@ async def test_add_product_to_product_set_async_use_cached_wrapped_rpc(transport 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) @@ -6136,8 +6857,12 @@ async def test_add_product_to_product_set_async_use_cached_wrapped_rpc(transport 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, @@ -6149,8 +6874,8 @@ async def test_add_product_to_product_set_async(transport: str = 'grpc_asyncio', # 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) @@ -6169,6 +6894,7 @@ async def test_add_product_to_product_set_async(transport: str = 'grpc_asyncio', 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(), @@ -6178,12 +6904,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) @@ -6195,9 +6921,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 @@ -6210,12 +6936,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) @@ -6227,9 +6953,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(): @@ -6239,15 +6965,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 @@ -6255,10 +6981,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 @@ -6272,10 +6998,11 @@ 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( @@ -6284,8 +7011,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 @@ -6293,8 +7020,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 @@ -6302,12 +7029,13 @@ 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( @@ -6319,16 +7047,19 @@ 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, @@ -6340,8 +7071,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) @@ -6361,30 +7092,33 @@ 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 @@ -6399,12 +7133,19 @@ 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) @@ -6417,8 +7158,11 @@ 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: @@ -6432,12 +7176,17 @@ async def test_remove_product_from_product_set_async_use_cached_wrapped_rpc(tran 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) @@ -6451,8 +7200,12 @@ async def test_remove_product_from_product_set_async_use_cached_wrapped_rpc(tran 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, @@ -6464,8 +7217,8 @@ async def test_remove_product_from_product_set_async(transport: str = 'grpc_asyn # 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) @@ -6484,6 +7237,7 @@ async def test_remove_product_from_product_set_async(transport: str = 'grpc_asyn 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(), @@ -6493,12 +7247,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) @@ -6510,9 +7264,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 @@ -6525,12 +7279,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) @@ -6542,9 +7296,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(): @@ -6554,15 +7308,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 @@ -6570,10 +7324,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 @@ -6587,10 +7341,11 @@ 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( @@ -6599,8 +7354,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 @@ -6608,8 +7363,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 @@ -6617,12 +7372,13 @@ 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( @@ -6634,16 +7390,19 @@ 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, @@ -6655,11 +7414,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) @@ -6671,7 +7430,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(): @@ -6679,30 +7438,33 @@ 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 @@ -6717,12 +7479,19 @@ 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) @@ -6735,8 +7504,11 @@ 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: @@ -6750,12 +7522,17 @@ async def test_list_products_in_product_set_async_use_cached_wrapped_rpc(transpo 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) @@ -6769,8 +7546,12 @@ async def test_list_products_in_product_set_async_use_cached_wrapped_rpc(transpo 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, @@ -6782,12 +7563,14 @@ async def test_list_products_in_product_set_async(transport: str = 'grpc_asyncio # 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. @@ -6798,13 +7581,14 @@ async def test_list_products_in_product_set_async(transport: str = 'grpc_asyncio # 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(), @@ -6814,12 +7598,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) @@ -6831,9 +7615,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 @@ -6846,13 +7630,15 @@ 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. @@ -6863,9 +7649,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(): @@ -6875,14 +7661,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 @@ -6890,7 +7676,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 @@ -6904,9 +7690,10 @@ 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( @@ -6915,16 +7702,18 @@ 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 @@ -6932,9 +7721,10 @@ 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( @@ -6946,7 +7736,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", ) @@ -6958,8 +7748,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( @@ -6968,17 +7758,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=[ @@ -6993,11 +7783,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', ''), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", ""),)), + ) + pager = client.list_products_in_product_set( + request={}, retry=retry, timeout=timeout ) - pager = client.list_products_in_product_set(request={}, retry=retry, timeout=timeout) assert pager._metadata == expected_metadata assert pager._retry == retry @@ -7005,8 +7795,9 @@ 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(), @@ -7015,8 +7806,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( @@ -7025,17 +7816,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=[ @@ -7046,9 +7837,10 @@ 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( @@ -7057,8 +7849,10 @@ 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( @@ -7067,17 +7861,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=[ @@ -7087,15 +7881,16 @@ 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 @@ -7106,8 +7901,10 @@ 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( @@ -7116,17 +7913,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=[ @@ -7139,18 +7936,22 @@ 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, @@ -7162,10 +7963,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. @@ -7183,28 +7984,31 @@ 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 @@ -7219,12 +8023,18 @@ 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) @@ -7242,8 +8052,11 @@ 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: @@ -7257,12 +8070,17 @@ async def test_import_product_sets_async_use_cached_wrapped_rpc(transport: str = 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) @@ -7281,8 +8099,12 @@ async def test_import_product_sets_async_use_cached_wrapped_rpc(transport: str = 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, @@ -7294,11 +8116,11 @@ async def test_import_product_sets_async(transport: str = 'grpc_asyncio', reques # 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) @@ -7316,6 +8138,7 @@ async def test_import_product_sets_async(transport: str = 'grpc_asyncio', reques 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(), @@ -7325,13 +8148,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. @@ -7342,9 +8165,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 @@ -7357,13 +8180,15 @@ 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. @@ -7374,9 +8199,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(): @@ -7386,15 +8211,19 @@ 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 @@ -7402,10 +8231,14 @@ 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 @@ -7419,10 +8252,15 @@ 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( @@ -7431,19 +8269,23 @@ 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 @@ -7451,12 +8293,17 @@ 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( @@ -7468,8 +8315,12 @@ 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" + ) + ), ) @@ -7487,12 +8338,18 @@ 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) @@ -7507,59 +8364,64 @@ 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() @@ -7569,24 +8431,32 @@ def test_create_product_set_rest_required_fields(request_type=product_search_ser 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(): @@ -7596,18 +8466,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) @@ -7617,7 +8487,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"} @@ -7627,10 +8497,14 @@ 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, @@ -7641,9 +8515,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", ) @@ -7665,8 +8539,12 @@ 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) @@ -7681,57 +8559,67 @@ 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 @@ -7739,27 +8627,37 @@ def test_list_product_sets_rest_required_fields(request_type=product_search_serv 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(): @@ -7769,16 +8667,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) @@ -7788,7 +8686,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"} @@ -7798,10 +8696,14 @@ 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, @@ -7812,20 +8714,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( @@ -7834,17 +8736,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=[ @@ -7857,24 +8759,25 @@ 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 @@ -7896,7 +8799,9 @@ 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 = {} @@ -7912,55 +8817,60 @@ 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 @@ -7971,24 +8881,24 @@ def test_get_product_set_rest_required_fields(request_type=product_search_servic 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(): @@ -7998,16 +8908,18 @@ 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) @@ -8017,7 +8929,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"} @@ -8027,10 +8939,14 @@ 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, @@ -8041,7 +8957,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", ) @@ -8059,12 +8975,18 @@ 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) @@ -8079,54 +9001,59 @@ 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() @@ -8136,24 +9063,24 @@ def test_update_product_set_rest_required_fields(request_type=product_search_ser 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(): @@ -8163,17 +9090,21 @@ 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) @@ -8183,7 +9114,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"} @@ -8193,10 +9124,14 @@ 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, @@ -8207,8 +9142,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"]), ) @@ -8226,12 +9161,18 @@ 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) @@ -8246,80 +9187,85 @@ 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(): @@ -8329,24 +9275,26 @@ 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"} @@ -8356,10 +9304,14 @@ 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, @@ -8370,7 +9322,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", ) @@ -8392,7 +9344,9 @@ 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 = {} @@ -8408,59 +9362,64 @@ 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() @@ -8470,24 +9429,32 @@ def test_create_product_rest_required_fields(request_type=product_search_service 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(): @@ -8497,18 +9464,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) @@ -8518,7 +9485,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"} @@ -8528,10 +9495,14 @@ 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, @@ -8542,9 +9513,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", ) @@ -8566,7 +9537,9 @@ 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 = {} @@ -8582,57 +9555,67 @@ 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 @@ -8643,24 +9626,32 @@ def test_list_products_rest_required_fields(request_type=product_search_service. 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(): @@ -8670,16 +9661,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) @@ -8689,7 +9680,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"} @@ -8699,10 +9690,14 @@ 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, @@ -8713,20 +9708,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( @@ -8735,17 +9730,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=[ @@ -8758,24 +9753,25 @@ 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 @@ -8797,7 +9793,9 @@ 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 = {} @@ -8813,55 +9811,60 @@ 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 @@ -8872,24 +9875,24 @@ def test_get_product_rest_required_fields(request_type=product_search_service.Ge 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(): @@ -8899,16 +9902,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) @@ -8918,7 +9921,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"} @@ -8928,10 +9931,14 @@ 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, @@ -8942,7 +9949,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", ) @@ -8964,7 +9971,9 @@ 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 = {} @@ -8980,54 +9989,59 @@ 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() @@ -9037,24 +10051,24 @@ def test_update_product_rest_required_fields(request_type=product_search_service 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(): @@ -9064,17 +10078,19 @@ 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) @@ -9084,7 +10100,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"} @@ -9094,10 +10110,14 @@ 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, @@ -9108,8 +10128,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"]), ) @@ -9131,7 +10151,9 @@ 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 = {} @@ -9147,80 +10169,85 @@ 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(): @@ -9230,24 +10257,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"} @@ -9257,10 +10284,14 @@ 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, @@ -9271,7 +10302,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", ) @@ -9289,12 +10320,19 @@ 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) @@ -9309,59 +10347,64 @@ 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() @@ -9371,24 +10414,32 @@ def test_create_reference_image_rest_required_fields(request_type=product_search 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(): @@ -9398,18 +10449,20 @@ 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) @@ -9419,7 +10472,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"} @@ -9429,10 +10482,14 @@ 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, @@ -9443,9 +10500,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", ) @@ -9463,12 +10520,19 @@ 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) @@ -9483,80 +10547,85 @@ 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(): @@ -9566,24 +10635,26 @@ 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"} @@ -9593,10 +10664,14 @@ 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, @@ -9607,7 +10682,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", ) @@ -9625,12 +10700,19 @@ 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) @@ -9645,57 +10727,67 @@ 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 @@ -9703,27 +10795,37 @@ def test_list_reference_images_rest_required_fields(request_type=product_search_ 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(): @@ -9733,16 +10835,18 @@ 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) @@ -9750,9 +10854,11 @@ 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"} @@ -9762,10 +10868,14 @@ 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, @@ -9776,20 +10886,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( @@ -9798,17 +10908,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=[ @@ -9821,24 +10931,30 @@ 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 @@ -9856,12 +10972,18 @@ 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) @@ -9876,55 +10998,60 @@ 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 @@ -9935,24 +11062,24 @@ def test_get_reference_image_rest_required_fields(request_type=product_search_se 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(): @@ -9962,16 +11089,18 @@ 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) @@ -9981,7 +11110,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"} @@ -9991,10 +11120,14 @@ 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, @@ -10005,7 +11138,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", ) @@ -10023,12 +11156,19 @@ 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) @@ -10043,7 +11183,9 @@ 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 = {} @@ -10051,77 +11193,88 @@ def test_add_product_to_product_set_rest_required_fields(request_type=product_se 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(): @@ -10131,25 +11284,27 @@ 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"} @@ -10159,10 +11314,14 @@ 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, @@ -10173,8 +11332,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", ) @@ -10192,12 +11351,19 @@ 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) @@ -10212,7 +11378,9 @@ 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 = {} @@ -10220,77 +11388,90 @@ def test_remove_product_from_product_set_rest_required_fields(request_type=produ 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(): @@ -10300,25 +11481,27 @@ 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"} @@ -10328,10 +11511,14 @@ 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, @@ -10342,8 +11529,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", ) @@ -10361,12 +11548,19 @@ 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) @@ -10381,57 +11575,67 @@ 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 @@ -10439,27 +11643,37 @@ def test_list_products_in_product_set_rest_required_fields(request_type=product_ 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(): @@ -10469,16 +11683,18 @@ 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) @@ -10486,9 +11702,11 @@ 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"} @@ -10498,10 +11716,14 @@ 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, @@ -10512,20 +11734,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( @@ -10534,17 +11756,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=[ @@ -10557,24 +11779,28 @@ 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 @@ -10592,12 +11818,18 @@ 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) @@ -10616,81 +11848,94 @@ 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(): @@ -10700,17 +11945,21 @@ 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) @@ -10718,7 +11967,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"} @@ -10728,10 +11977,14 @@ 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, @@ -10742,8 +11995,12 @@ 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" + ) + ), ) @@ -10785,8 +12042,7 @@ 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. @@ -10808,6 +12064,7 @@ 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( @@ -10822,18 +12079,23 @@ 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() @@ -10843,8 +12105,7 @@ 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 @@ -10859,8 +12120,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) @@ -10882,8 +12143,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) @@ -10904,9 +12165,7 @@ 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) @@ -10928,8 +12187,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) @@ -10951,8 +12210,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) @@ -10973,9 +12232,7 @@ 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) @@ -10996,9 +12253,7 @@ 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) @@ -11019,9 +12274,7 @@ 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) @@ -11042,9 +12295,7 @@ 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) @@ -11065,9 +12316,7 @@ 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) @@ -11089,8 +12338,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) @@ -11112,8 +12361,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) @@ -11135,8 +12384,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) @@ -11158,8 +12407,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) @@ -11181,8 +12430,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) @@ -11204,8 +12453,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) @@ -11227,8 +12476,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) @@ -11250,9 +12499,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. @@ -11272,8 +12521,7 @@ 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 @@ -11289,13 +12537,15 @@ 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. @@ -11317,12 +12567,14 @@ 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. @@ -11343,14 +12595,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. @@ -11372,13 +12624,15 @@ 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. @@ -11400,8 +12654,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) @@ -11424,16 +12678,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. @@ -11454,13 +12708,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. @@ -11481,16 +12735,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. @@ -11511,16 +12765,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. @@ -11541,9 +12795,7 @@ 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) @@ -11567,13 +12819,15 @@ 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. @@ -11595,8 +12849,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) @@ -11620,13 +12874,15 @@ 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. @@ -11648,13 +12904,15 @@ 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. @@ -11676,8 +12934,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) @@ -11701,8 +12959,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) @@ -11726,12 +12984,14 @@ 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. @@ -11753,11 +13013,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) @@ -11776,20 +13036,24 @@ 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() @@ -11798,25 +13062,43 @@ def test_create_product_set_rest_bad_request(request_type=product_search_service 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 @@ -11830,7 +13112,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 @@ -11844,7 +13126,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 @@ -11859,12 +13141,16 @@ 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") @@ -11877,11 +13163,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 @@ -11891,34 +13177,47 @@ 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", @@ -11929,11 +13228,13 @@ 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"), ] @@ -11941,27 +13242,37 @@ 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() @@ -11970,25 +13281,27 @@ def test_list_product_sets_rest_bad_request(request_type=product_search_service. 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 @@ -11998,33 +13311,46 @@ 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", @@ -12035,39 +13361,54 @@ 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() @@ -12076,26 +13417,28 @@ def test_get_product_set_rest_bad_request(request_type=product_search_service.Ge 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 @@ -12105,34 +13448,47 @@ 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", @@ -12143,11 +13499,13 @@ 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"), ] @@ -12155,27 +13513,41 @@ 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() @@ -12184,25 +13556,47 @@ def test_update_product_set_rest_bad_request(request_type=product_search_service 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 @@ -12216,7 +13610,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 @@ -12230,7 +13624,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 @@ -12245,12 +13639,16 @@ 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") @@ -12263,11 +13661,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 @@ -12277,34 +13675,47 @@ 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", @@ -12315,11 +13726,13 @@ 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"), ] @@ -12327,27 +13740,37 @@ 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() @@ -12356,30 +13779,32 @@ def test_delete_product_set_rest_bad_request(request_type=product_search_service 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) @@ -12392,15 +13817,23 @@ 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", @@ -12413,31 +13846,41 @@ 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() @@ -12446,19 +13889,27 @@ def test_create_product_rest_bad_request(request_type=product_search_service.Cre 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 @@ -12478,7 +13929,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 @@ -12492,7 +13943,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 @@ -12507,12 +13958,16 @@ 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") @@ -12525,13 +13980,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 @@ -12541,36 +13996,48 @@ 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", @@ -12581,11 +14048,13 @@ 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"), ] @@ -12593,27 +14062,37 @@ 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() @@ -12622,25 +14101,27 @@ def test_list_products_rest_bad_request(request_type=product_search_service.List 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 @@ -12650,33 +14131,45 @@ 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", @@ -12687,39 +14180,54 @@ 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() @@ -12728,28 +14236,30 @@ def test_get_product_rest_bad_request(request_type=product_search_service.GetPro 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 @@ -12759,36 +14269,48 @@ 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", @@ -12799,11 +14321,13 @@ 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"), ] @@ -12811,27 +14335,39 @@ 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() @@ -12840,19 +14376,29 @@ def test_update_product_rest_bad_request(request_type=product_search_service.Upd 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 @@ -12872,7 +14418,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 @@ -12886,7 +14432,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 @@ -12901,12 +14447,16 @@ 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") @@ -12919,13 +14469,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 @@ -12935,36 +14485,48 @@ 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", @@ -12975,11 +14537,13 @@ 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"), ] @@ -12987,27 +14551,37 @@ 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() @@ -13016,30 +14590,32 @@ def test_delete_product_rest_bad_request(request_type=product_search_service.Del 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) @@ -13052,15 +14628,23 @@ 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", @@ -13073,31 +14657,41 @@ 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() @@ -13106,25 +14700,38 @@ def test_create_reference_image_rest_bad_request(request_type=product_search_ser 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 @@ -13138,7 +14745,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 @@ -13152,7 +14759,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 @@ -13167,12 +14774,16 @@ 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") @@ -13185,11 +14796,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 @@ -13199,34 +14810,47 @@ 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", @@ -13237,39 +14861,56 @@ 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() @@ -13278,30 +14919,34 @@ def test_delete_reference_image_rest_bad_request(request_type=product_search_ser 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) @@ -13314,15 +14959,23 @@ 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", @@ -13335,31 +14988,41 @@ 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() @@ -13368,26 +15031,28 @@ def test_list_reference_images_rest_bad_request(request_type=product_search_serv 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 @@ -13395,9 +15060,11 @@ 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) @@ -13405,26 +15072,39 @@ 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", @@ -13435,39 +15115,56 @@ 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() @@ -13476,26 +15173,30 @@ def test_get_reference_image_rest_bad_request(request_type=product_search_servic 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 @@ -13505,34 +15206,47 @@ 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", @@ -13543,39 +15257,54 @@ 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() @@ -13584,30 +15313,32 @@ def test_add_product_to_product_set_rest_bad_request(request_type=product_search 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) @@ -13620,15 +15351,23 @@ 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", @@ -13641,31 +15380,41 @@ 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() @@ -13674,30 +15423,32 @@ def test_remove_product_from_product_set_rest_bad_request(request_type=product_s 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) @@ -13710,15 +15461,24 @@ 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", @@ -13731,31 +15491,41 @@ 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() @@ -13764,25 +15534,27 @@ def test_list_products_in_product_set_rest_bad_request(request_type=product_sear 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 @@ -13790,35 +15562,50 @@ 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", @@ -13829,39 +15616,54 @@ 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() @@ -13870,30 +15672,32 @@ def test_import_product_sets_rest_bad_request(request_type=product_search_servic 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) @@ -13906,20 +15710,33 @@ 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", @@ -13934,7 +15751,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"), ] @@ -13942,16 +15759,22 @@ 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 @@ -13966,8 +15789,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. @@ -13988,8 +15811,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. @@ -14009,9 +15832,7 @@ 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. @@ -14032,8 +15853,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. @@ -14054,8 +15875,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. @@ -14075,9 +15896,7 @@ 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. @@ -14097,9 +15916,7 @@ 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. @@ -14119,9 +15936,7 @@ 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. @@ -14141,9 +15956,7 @@ 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. @@ -14163,9 +15976,7 @@ 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. @@ -14186,8 +15997,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. @@ -14208,8 +16019,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. @@ -14230,8 +16041,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. @@ -14252,8 +16063,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. @@ -14274,8 +16085,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. @@ -14296,8 +16107,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. @@ -14318,8 +16129,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. @@ -14340,8 +16151,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. @@ -14362,12 +16173,13 @@ 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( @@ -14378,18 +16190,21 @@ 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(), @@ -14398,24 +16213,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): @@ -14431,7 +16246,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): @@ -14440,26 +16255,39 @@ 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() @@ -14468,15 +16296,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, ) @@ -14491,12 +16319,15 @@ 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", ) @@ -14510,39 +16341,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( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: + 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", @@ -14550,9 +16381,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, @@ -14563,10 +16394,14 @@ 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. @@ -14575,7 +16410,7 @@ def test_product_search_grpc_transport_client_cert_source_for_mtls( 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", @@ -14596,61 +16431,77 @@ def test_product_search_grpc_transport_client_cert_source_for_mtls( 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() @@ -14716,8 +16567,10 @@ 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( @@ -14730,7 +16583,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( @@ -14745,12 +16598,20 @@ 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 @@ -14759,7 +16620,7 @@ def test_product_search_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", @@ -14789,17 +16650,23 @@ def test_product_search_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.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() @@ -14830,7 +16697,7 @@ def test_product_search_transport_channel_mtls_with_adc( def test_product_search_grpc_lro_client(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) transport = client.transport @@ -14847,7 +16714,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 @@ -14865,7 +16732,11 @@ 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 @@ -14882,11 +16753,18 @@ 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 @@ -14903,13 +16781,21 @@ 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 @@ -14926,9 +16812,12 @@ 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 @@ -14943,9 +16832,12 @@ 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 @@ -14960,9 +16852,12 @@ 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 @@ -14977,9 +16872,12 @@ 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 @@ -14994,10 +16892,14 @@ 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 @@ -15017,14 +16919,18 @@ 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(), @@ -15035,10 +16941,11 @@ 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() @@ -15047,10 +16954,11 @@ 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() @@ -15058,10 +16966,11 @@ 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() @@ -15069,13 +16978,12 @@ 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: @@ -15084,10 +16992,14 @@ 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 @@ -15102,7 +17014,9 @@ 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 191773d5572d..cbf94b283c70 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,4 +1,3 @@ - # -*- 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 61e00fec874e..6396bb4b7f9a 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,6 +14,7 @@ # limitations under the License. # import os + # try/except added for compatibility with python < 3.8 try: from unittest import mock @@ -21,53 +22,58 @@ except ImportError: # pragma: NO COVER import mock -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format import json import math +from collections.abc import AsyncIterable, Iterable + +import grpc import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule +from grpc.experimental import aio from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response from requests.sessions import Session + +from google.api_core import api_core_version 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 client_options +import google.auth +from google.api_core import ( + client_options, + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operation_async, # type: ignore + operations_v1, + path_template, +) 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 from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError -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.cloud.vision_v1p4beta1.services.image_annotator import ( + ImageAnnotatorAsyncClient, + ImageAnnotatorClient, + transports, +) +from google.cloud.vision_v1p4beta1.types import ( + face, + geometry, + image_annotator, + 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 - - CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -82,9 +88,11 @@ 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(): @@ -92,17 +100,27 @@ 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(): @@ -113,20 +131,43 @@ 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"} @@ -140,27 +181,46 @@ 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, - "auto", + "never", 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(): @@ -169,7 +229,9 @@ 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. @@ -177,7 +239,9 @@ 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 @@ -189,7 +253,9 @@ 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 @@ -201,7 +267,9 @@ 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 @@ -213,7 +281,9 @@ 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 @@ -228,83 +298,167 @@ 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) @@ -320,7 +474,8 @@ 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") @@ -333,14 +488,20 @@ 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) @@ -348,52 +509,68 @@ 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" ) @@ -409,30 +586,45 @@ 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( @@ -450,13 +642,15 @@ def test_image_annotator_client_client_options(client_class, transport_class, tr # 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, @@ -468,7 +662,7 @@ def test_image_annotator_client_client_options(client_class, transport_class, tr # 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( @@ -488,17 +682,22 @@ def test_image_annotator_client_client_options(client_class, transport_class, tr 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", @@ -507,48 +706,82 @@ def test_image_annotator_client_client_options(client_class, transport_class, tr 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 @@ -567,12 +800,22 @@ def test_image_annotator_client_mtls_env_auto(client_class, transport_class, tra # 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 @@ -593,15 +836,22 @@ def test_image_annotator_client_mtls_env_auto(client_class, transport_class, tra ) # 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, @@ -611,19 +861,31 @@ def test_image_annotator_client_mtls_env_auto(client_class, transport_class, tra ) -@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 @@ -631,18 +893,25 @@ 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 @@ -679,23 +948,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 = [ @@ -726,23 +995,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"}): @@ -758,16 +1027,27 @@ 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 @@ -777,27 +1057,50 @@ 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", @@ -820,11 +1123,19 @@ 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. @@ -832,27 +1143,40 @@ 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, @@ -861,24 +1185,40 @@ def test_image_annotator_client_client_options_scopes(client_class, transport_cl 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, @@ -887,11 +1227,14 @@ def test_image_annotator_client_client_options_credentials_file(client_class, tr 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, @@ -906,23 +1249,38 @@ 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, @@ -932,13 +1290,13 @@ def test_image_annotator_client_create_channel_credentials_file(client_class, tr ) # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object(grpc_helpers, "create_channel") as create_channel, + ): creds = ga_credentials.AnonymousCredentials() file_creds = ga_credentials.AnonymousCredentials() load_creds.return_value = (file_creds, None) @@ -950,9 +1308,9 @@ def test_image_annotator_client_create_channel_credentials_file(client_class, tr 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, @@ -963,11 +1321,14 @@ def test_image_annotator_client_create_channel_credentials_file(client_class, tr ) -@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, @@ -979,11 +1340,10 @@ 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. @@ -1001,25 +1361,26 @@ 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, @@ -1035,12 +1396,19 @@ 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) @@ -1053,8 +1421,11 @@ 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: @@ -1068,12 +1439,17 @@ async def test_batch_annotate_images_async_use_cached_wrapped_rpc(transport: str 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) @@ -1087,8 +1463,12 @@ async def test_batch_annotate_images_async_use_cached_wrapped_rpc(transport: str 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, @@ -1100,11 +1480,12 @@ async def test_batch_annotate_images_async(transport: str = 'grpc_asyncio', requ # 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. @@ -1129,14 +1510,18 @@ 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 @@ -1144,7 +1529,11 @@ 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 @@ -1158,9 +1547,14 @@ 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( @@ -1169,16 +1563,22 @@ 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 @@ -1186,9 +1586,14 @@ 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( @@ -1200,15 +1605,22 @@ 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, @@ -1220,11 +1632,10 @@ 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. @@ -1242,25 +1653,26 @@ 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, @@ -1276,12 +1688,18 @@ 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) @@ -1294,8 +1712,11 @@ 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: @@ -1309,12 +1730,17 @@ async def test_batch_annotate_files_async_use_cached_wrapped_rpc(transport: str 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) @@ -1328,8 +1754,12 @@ async def test_batch_annotate_files_async_use_cached_wrapped_rpc(transport: str 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, @@ -1341,11 +1771,12 @@ async def test_batch_annotate_files_async(transport: str = 'grpc_asyncio', reque # 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. @@ -1370,14 +1801,20 @@ 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 @@ -1385,7 +1822,13 @@ 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 @@ -1399,9 +1842,16 @@ 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( @@ -1410,16 +1860,24 @@ 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 @@ -1427,9 +1885,16 @@ 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( @@ -1441,15 +1906,24 @@ 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, @@ -1461,10 +1935,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. @@ -1482,25 +1956,26 @@ 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, @@ -1516,12 +1991,19 @@ 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) @@ -1539,8 +2021,11 @@ 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: @@ -1554,12 +2039,17 @@ async def test_async_batch_annotate_images_async_use_cached_wrapped_rpc(transpor 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) @@ -1578,8 +2068,12 @@ async def test_async_batch_annotate_images_async_use_cached_wrapped_rpc(transpor 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, @@ -1591,11 +2085,11 @@ async def test_async_batch_annotate_images_async(transport: str = 'grpc_asyncio' # 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) @@ -1621,15 +2115,21 @@ 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 @@ -1637,10 +2137,16 @@ 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 @@ -1654,10 +2160,17 @@ 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( @@ -1666,19 +2179,25 @@ 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 @@ -1686,12 +2205,19 @@ 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( @@ -1703,16 +2229,25 @@ 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, @@ -1724,10 +2259,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. @@ -1745,25 +2280,26 @@ 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, @@ -1779,12 +2315,19 @@ 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) @@ -1802,8 +2345,11 @@ 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: @@ -1817,12 +2363,17 @@ async def test_async_batch_annotate_files_async_use_cached_wrapped_rpc(transport 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) @@ -1841,8 +2392,12 @@ async def test_async_batch_annotate_files_async_use_cached_wrapped_rpc(transport 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, @@ -1854,11 +2409,11 @@ async def test_async_batch_annotate_files_async(transport: str = 'grpc_asyncio', # 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) @@ -1884,14 +2439,20 @@ 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 @@ -1899,7 +2460,13 @@ 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 @@ -1913,9 +2480,16 @@ 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( @@ -1924,18 +2498,24 @@ 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 @@ -1943,9 +2523,16 @@ 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( @@ -1957,7 +2544,13 @@ 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") + ) + ) + ], ) @@ -1975,12 +2568,19 @@ 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) @@ -1995,52 +2595,57 @@ 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() @@ -2050,24 +2655,24 @@ def test_batch_annotate_images_rest_required_fields(request_type=image_annotator 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(): @@ -2077,7 +2682,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() @@ -2086,7 +2691,11 @@ 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) @@ -2096,7 +2705,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"} @@ -2106,10 +2715,12 @@ 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, @@ -2120,7 +2731,11 @@ 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") + ) + ], ) @@ -2138,12 +2753,18 @@ 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) @@ -2158,52 +2779,57 @@ 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() @@ -2213,24 +2839,24 @@ def test_batch_annotate_files_rest_required_fields(request_type=image_annotator. 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(): @@ -2240,7 +2866,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() @@ -2249,7 +2875,13 @@ 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) @@ -2259,7 +2891,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"} @@ -2269,10 +2901,12 @@ 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, @@ -2283,7 +2917,13 @@ 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") + ) + ) + ], ) @@ -2301,12 +2941,19 @@ 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) @@ -2325,76 +2972,89 @@ 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(): @@ -2404,17 +3064,23 @@ 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) @@ -2422,7 +3088,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"} @@ -2432,10 +3098,12 @@ 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, @@ -2446,8 +3114,14 @@ 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") + ), ) @@ -2465,12 +3139,19 @@ 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) @@ -2489,76 +3170,81 @@ 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(): @@ -2568,16 +3254,22 @@ 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) @@ -2585,7 +3277,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"} @@ -2595,10 +3287,12 @@ 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, @@ -2609,7 +3303,13 @@ 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") + ) + ) + ], ) @@ -2651,8 +3351,7 @@ 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. @@ -2674,6 +3373,7 @@ 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( @@ -2688,18 +3388,23 @@ 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() @@ -2709,8 +3414,7 @@ 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 @@ -2725,8 +3429,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) @@ -2748,8 +3452,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) @@ -2771,9 +3475,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. @@ -2794,9 +3498,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. @@ -2816,8 +3520,7 @@ 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 @@ -2833,11 +3536,12 @@ 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. @@ -2859,11 +3563,12 @@ 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. @@ -2885,11 +3590,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) @@ -2912,11 +3617,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) @@ -2935,20 +3640,24 @@ 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() @@ -2957,14 +3666,16 @@ def test_batch_annotate_images_rest_bad_request(request_type=image_annotator.Bat 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 @@ -2972,10 +3683,9 @@ 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() @@ -2984,7 +3694,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) @@ -2997,19 +3707,32 @@ 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", @@ -3020,39 +3743,54 @@ 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() @@ -3061,14 +3799,16 @@ def test_batch_annotate_files_rest_bad_request(request_type=image_annotator.Batc 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 @@ -3076,10 +3816,9 @@ 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() @@ -3088,7 +3827,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) @@ -3101,19 +3840,32 @@ 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", @@ -3124,39 +3876,54 @@ 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() @@ -3165,14 +3932,16 @@ def test_async_batch_annotate_images_rest_bad_request(request_type=image_annotat 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 @@ -3180,15 +3949,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) @@ -3201,20 +3970,33 @@ 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", @@ -3229,7 +4011,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"), ] @@ -3237,27 +4019,37 @@ 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() @@ -3266,14 +4058,16 @@ def test_async_batch_annotate_files_rest_bad_request(request_type=image_annotato 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 @@ -3281,15 +4075,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) @@ -3302,20 +4096,33 @@ 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", @@ -3330,7 +4137,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"), ] @@ -3338,16 +4145,22 @@ 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 @@ -3362,8 +4175,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. @@ -3384,8 +4197,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. @@ -3406,8 +4219,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. @@ -3428,8 +4241,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. @@ -3450,12 +4263,13 @@ 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( @@ -3466,18 +4280,21 @@ 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(), @@ -3486,10 +4303,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): @@ -3505,7 +4322,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): @@ -3514,26 +4331,39 @@ 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() @@ -3542,15 +4372,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, ) @@ -3565,12 +4395,15 @@ 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", ) @@ -3584,39 +4417,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( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: + 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", @@ -3624,9 +4457,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, @@ -3637,10 +4470,14 @@ 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. @@ -3649,7 +4486,7 @@ def test_image_annotator_grpc_transport_client_cert_source_for_mtls( 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", @@ -3670,61 +4507,77 @@ def test_image_annotator_grpc_transport_client_cert_source_for_mtls( 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() @@ -3748,8 +4601,10 @@ 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( @@ -3762,7 +4617,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( @@ -3777,12 +4632,22 @@ 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 @@ -3791,7 +4656,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", @@ -3821,17 +4686,23 @@ 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() @@ -3862,7 +4733,7 @@ def test_image_annotator_transport_channel_mtls_with_adc( def test_image_annotator_grpc_lro_client(): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) transport = client.transport @@ -3879,7 +4750,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 @@ -3897,7 +4768,11 @@ 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 @@ -3914,11 +4789,18 @@ 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 @@ -3935,9 +4817,12 @@ 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 @@ -3952,9 +4837,12 @@ 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 @@ -3969,9 +4857,12 @@ 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 @@ -3986,9 +4877,12 @@ 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 @@ -4003,10 +4897,14 @@ 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 @@ -4026,14 +4924,18 @@ 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(), @@ -4044,10 +4946,11 @@ 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() @@ -4056,10 +4959,11 @@ 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() @@ -4067,10 +4971,11 @@ 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() @@ -4078,13 +4983,12 @@ 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: @@ -4093,10 +4997,14 @@ 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 @@ -4111,7 +5019,9 @@ 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 7ed8bec55a57..8e5e9d41995e 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,6 +14,7 @@ # limitations under the License. # import os + # try/except added for compatibility with python < 3.8 try: from unittest import mock @@ -21,56 +22,60 @@ except ImportError: # pragma: NO COVER import mock -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format import json import math +from collections.abc import AsyncIterable, Iterable + +import grpc import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule +from grpc.experimental import aio from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response from requests.sessions import Session + +from google.api_core import api_core_version 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 client_options +import google.auth +from google.api_core import ( + client_options, + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operation_async, # type: ignore + operations_v1, + path_template, +) 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 from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError -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.cloud.vision_v1p4beta1.services.product_search import ( + ProductSearchAsyncClient, + ProductSearchClient, + pagers, + transports, +) +from google.cloud.vision_v1p4beta1.types import geometry, 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.protobuf import ( + any_pb2, # type: ignore + empty_pb2, # type: ignore + field_mask_pb2, # type: ignore + timestamp_pb2, # type: ignore +) from google.rpc import status_pb2 # type: ignore -import google.auth - - CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -85,9 +90,11 @@ 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,17 +102,27 @@ 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,11 +133,26 @@ 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) @@ -129,7 +161,11 @@ 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"} @@ -143,27 +179,46 @@ 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, - "auto", + "never", 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(): @@ -172,7 +227,9 @@ 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. @@ -180,7 +237,9 @@ 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 @@ -192,7 +251,9 @@ 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 @@ -204,7 +265,9 @@ 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 @@ -216,7 +279,9 @@ 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 @@ -231,83 +296,167 @@ 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) @@ -323,7 +472,8 @@ 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") @@ -336,14 +486,20 @@ 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) @@ -351,52 +507,68 @@ 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" ) @@ -412,30 +584,45 @@ 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( @@ -453,13 +640,15 @@ def test_product_search_client_client_options(client_class, transport_class, tra # 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, @@ -471,7 +660,7 @@ def test_product_search_client_client_options(client_class, transport_class, tra # 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( @@ -491,17 +680,22 @@ def test_product_search_client_client_options(client_class, transport_class, tra 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", @@ -510,48 +704,82 @@ def test_product_search_client_client_options(client_class, transport_class, tra 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 @@ -570,12 +798,22 @@ def test_product_search_client_mtls_env_auto(client_class, transport_class, tran # 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 @@ -596,15 +834,22 @@ def test_product_search_client_mtls_env_auto(client_class, transport_class, tran ) # 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, @@ -614,19 +859,31 @@ def test_product_search_client_mtls_env_auto(client_class, transport_class, tran ) -@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 @@ -634,18 +891,25 @@ 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 @@ -682,23 +946,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 = [ @@ -729,23 +993,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"}): @@ -761,16 +1025,27 @@ 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 @@ -780,27 +1055,50 @@ 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", @@ -823,11 +1121,19 @@ 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. @@ -835,27 +1141,40 @@ 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, @@ -864,24 +1183,40 @@ def test_product_search_client_client_options_scopes(client_class, transport_cla 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, @@ -890,11 +1225,14 @@ def test_product_search_client_client_options_credentials_file(client_class, tra 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, @@ -909,23 +1247,38 @@ 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, @@ -935,13 +1288,13 @@ def test_product_search_client_create_channel_credentials_file(client_class, tra ) # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object(grpc_helpers, "create_channel") as create_channel, + ): creds = ga_credentials.AnonymousCredentials() file_creds = ga_credentials.AnonymousCredentials() load_creds.return_value = (file_creds, None) @@ -953,9 +1306,9 @@ def test_product_search_client_create_channel_credentials_file(client_class, tra 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, @@ -966,11 +1319,14 @@ def test_product_search_client_create_channel_credentials_file(client_class, tra ) -@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, @@ -982,12 +1338,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) @@ -999,8 +1355,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(): @@ -1008,30 +1364,33 @@ 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 @@ -1046,12 +1405,18 @@ 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) @@ -1064,8 +1429,11 @@ 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: @@ -1079,12 +1447,17 @@ async def test_create_product_set_async_use_cached_wrapped_rpc(transport: str = 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) @@ -1098,8 +1471,12 @@ async def test_create_product_set_async_use_cached_wrapped_rpc(transport: str = 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, @@ -1111,13 +1488,15 @@ async def test_create_product_set_async(transport: str = 'grpc_asyncio', request # 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. @@ -1128,14 +1507,15 @@ async def test_create_product_set_async(transport: str = 'grpc_asyncio', 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.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(), @@ -1145,12 +1525,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) @@ -1162,9 +1542,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 @@ -1177,13 +1557,15 @@ 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. @@ -1194,9 +1576,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(): @@ -1206,16 +1588,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 @@ -1223,13 +1605,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 @@ -1243,11 +1625,12 @@ 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( @@ -1256,18 +1639,20 @@ 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 @@ -1275,15 +1660,16 @@ 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( @@ -1295,17 +1681,20 @@ 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, @@ -1317,11 +1706,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) @@ -1333,7 +1722,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(): @@ -1341,30 +1730,33 @@ 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 @@ -1383,8 +1775,12 @@ 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) @@ -1397,8 +1793,11 @@ 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: @@ -1412,12 +1811,17 @@ async def test_list_product_sets_async_use_cached_wrapped_rpc(transport: str = " 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) @@ -1431,8 +1835,12 @@ async def test_list_product_sets_async_use_cached_wrapped_rpc(transport: str = " 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, @@ -1444,12 +1852,14 @@ async def test_list_product_sets_async(transport: str = 'grpc_asyncio', request_ # 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. @@ -1460,13 +1870,14 @@ async def test_list_product_sets_async(transport: str = 'grpc_asyncio', request_ # 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(), @@ -1476,12 +1887,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) @@ -1493,9 +1904,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 @@ -1508,13 +1919,15 @@ 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. @@ -1525,9 +1938,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(): @@ -1537,14 +1950,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 @@ -1552,7 +1965,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 @@ -1566,9 +1979,10 @@ 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( @@ -1577,16 +1991,18 @@ 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 @@ -1594,9 +2010,10 @@ 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( @@ -1608,7 +2025,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", ) @@ -1620,8 +2037,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( @@ -1630,17 +2047,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=[ @@ -1655,9 +2072,7 @@ 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) @@ -1667,8 +2082,9 @@ 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(), @@ -1677,8 +2093,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( @@ -1687,17 +2103,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=[ @@ -1708,9 +2124,10 @@ 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( @@ -1719,8 +2136,10 @@ 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( @@ -1729,17 +2148,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=[ @@ -1749,15 +2168,16 @@ 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 @@ -1768,8 +2188,10 @@ 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( @@ -1778,17 +2200,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=[ @@ -1801,18 +2223,22 @@ 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, @@ -1823,13 +2249,11 @@ 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) @@ -1841,8 +2265,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(): @@ -1850,28 +2274,29 @@ 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 @@ -1890,7 +2315,9 @@ 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) @@ -1904,8 +2331,11 @@ 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: @@ -1919,12 +2349,17 @@ async def test_get_product_set_async_use_cached_wrapped_rpc(transport: str = "gr 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) @@ -1938,8 +2373,12 @@ async def test_get_product_set_async_use_cached_wrapped_rpc(transport: str = "gr 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, @@ -1950,14 +2389,14 @@ async def test_get_product_set_async(transport: str = 'grpc_asyncio', request_ty 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. @@ -1968,14 +2407,15 @@ async def test_get_product_set_async(transport: str = 'grpc_asyncio', request_ty # 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(), @@ -1985,12 +2425,10 @@ 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) @@ -2002,9 +2440,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 @@ -2017,13 +2455,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. @@ -2034,9 +2472,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(): @@ -2045,15 +2483,13 @@ 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 @@ -2061,7 +2497,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 @@ -2075,9 +2511,10 @@ 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( @@ -2085,17 +2522,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 @@ -2103,9 +2540,10 @@ 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( @@ -2117,15 +2555,18 @@ 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, @@ -2137,12 +2578,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) @@ -2154,8 +2595,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(): @@ -2163,25 +2604,26 @@ 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, @@ -2197,12 +2639,18 @@ 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) @@ -2215,8 +2663,11 @@ 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: @@ -2230,12 +2681,17 @@ async def test_update_product_set_async_use_cached_wrapped_rpc(transport: str = 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) @@ -2249,8 +2705,12 @@ async def test_update_product_set_async_use_cached_wrapped_rpc(transport: str = 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, @@ -2262,13 +2722,15 @@ async def test_update_product_set_async(transport: str = 'grpc_asyncio', request # 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. @@ -2279,14 +2741,15 @@ async def test_update_product_set_async(transport: str = 'grpc_asyncio', 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.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(), @@ -2296,12 +2759,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) @@ -2313,9 +2776,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 @@ -2328,13 +2791,15 @@ 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. @@ -2345,9 +2810,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(): @@ -2357,15 +2822,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 @@ -2373,10 +2838,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 @@ -2390,10 +2855,11 @@ 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( @@ -2402,17 +2868,19 @@ 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 @@ -2420,12 +2888,13 @@ 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( @@ -2437,16 +2906,19 @@ 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, @@ -2458,8 +2930,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) @@ -2479,28 +2951,31 @@ 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 @@ -2515,12 +2990,18 @@ 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) @@ -2533,8 +3014,11 @@ 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: @@ -2548,12 +3032,17 @@ async def test_delete_product_set_async_use_cached_wrapped_rpc(transport: str = 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) @@ -2567,8 +3056,12 @@ async def test_delete_product_set_async_use_cached_wrapped_rpc(transport: str = 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, @@ -2580,8 +3073,8 @@ async def test_delete_product_set_async(transport: str = 'grpc_asyncio', request # 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) @@ -2600,6 +3093,7 @@ async def test_delete_product_set_async(transport: str = 'grpc_asyncio', request 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(), @@ -2609,12 +3103,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) @@ -2626,9 +3120,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 @@ -2641,12 +3135,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) @@ -2658,9 +3152,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(): @@ -2670,14 +3164,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 @@ -2685,7 +3179,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 @@ -2699,9 +3193,10 @@ 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( @@ -2710,8 +3205,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 @@ -2719,7 +3214,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 @@ -2727,9 +3222,10 @@ 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( @@ -2741,15 +3237,18 @@ 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, @@ -2760,15 +3259,13 @@ 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) @@ -2780,10 +3277,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(): @@ -2791,30 +3288,31 @@ 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 @@ -2833,7 +3331,9 @@ 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) @@ -2847,8 +3347,11 @@ 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: @@ -2862,12 +3365,17 @@ async def test_create_product_async_use_cached_wrapped_rpc(transport: str = "grp 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) @@ -2881,8 +3389,12 @@ async def test_create_product_async_use_cached_wrapped_rpc(transport: str = "grp 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, @@ -2893,16 +3405,16 @@ async def test_create_product_async(transport: str = 'grpc_asyncio', request_typ 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. @@ -2913,16 +3425,17 @@ async def test_create_product_async(transport: str = 'grpc_asyncio', request_typ # 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(), @@ -2932,12 +3445,10 @@ 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) @@ -2949,9 +3460,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 @@ -2964,13 +3475,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. @@ -2981,9 +3492,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(): @@ -2992,17 +3503,15 @@ 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 @@ -3010,13 +3519,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 @@ -3030,11 +3539,12 @@ 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( @@ -3042,19 +3552,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 @@ -3062,15 +3572,16 @@ 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( @@ -3082,17 +3593,20 @@ 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, @@ -3103,12 +3617,10 @@ 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) @@ -3120,7 +3632,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(): @@ -3128,30 +3640,31 @@ 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 @@ -3170,7 +3683,9 @@ 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) @@ -3184,8 +3699,11 @@ 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: @@ -3199,12 +3717,17 @@ async def test_list_products_async_use_cached_wrapped_rpc(transport: str = "grpc 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) @@ -3218,8 +3741,12 @@ async def test_list_products_async_use_cached_wrapped_rpc(transport: str = "grpc 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, @@ -3230,13 +3757,13 @@ async def test_list_products_async(transport: str = 'grpc_asyncio', request_type 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. @@ -3247,13 +3774,14 @@ async def test_list_products_async(transport: str = 'grpc_asyncio', request_type # 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(), @@ -3263,12 +3791,10 @@ 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) @@ -3280,9 +3806,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 @@ -3295,13 +3821,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. @@ -3312,9 +3838,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(): @@ -3323,15 +3849,13 @@ 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 @@ -3339,7 +3863,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 @@ -3353,9 +3877,10 @@ 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( @@ -3363,17 +3888,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 @@ -3381,9 +3906,10 @@ 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( @@ -3395,7 +3921,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", ) @@ -3406,9 +3932,7 @@ 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( @@ -3417,17 +3941,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=[ @@ -3442,9 +3966,7 @@ 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) @@ -3454,8 +3976,9 @@ 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(), @@ -3463,9 +3986,7 @@ 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( @@ -3474,17 +3995,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=[ @@ -3495,9 +4016,10 @@ 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( @@ -3506,8 +4028,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( @@ -3516,17 +4038,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=[ @@ -3536,15 +4058,16 @@ 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 @@ -3555,8 +4078,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( @@ -3565,17 +4088,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=[ @@ -3588,18 +4111,22 @@ 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, @@ -3610,15 +4137,13 @@ 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) @@ -3630,10 +4155,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(): @@ -3641,28 +4166,29 @@ 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 @@ -3681,7 +4207,9 @@ 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) @@ -3695,8 +4223,11 @@ 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: @@ -3710,12 +4241,17 @@ async def test_get_product_async_use_cached_wrapped_rpc(transport: str = "grpc_a 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) @@ -3729,8 +4265,12 @@ async def test_get_product_async_use_cached_wrapped_rpc(transport: str = "grpc_a 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, @@ -3741,16 +4281,16 @@ async def test_get_product_async(transport: str = 'grpc_asyncio', request_type=p 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. @@ -3761,16 +4301,17 @@ async def test_get_product_async(transport: str = 'grpc_asyncio', request_type=p # 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(), @@ -3780,12 +4321,10 @@ 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) @@ -3797,9 +4336,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 @@ -3812,13 +4351,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. @@ -3829,9 +4368,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(): @@ -3840,15 +4379,13 @@ 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 @@ -3856,7 +4393,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 @@ -3870,9 +4407,10 @@ 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( @@ -3880,17 +4418,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 @@ -3898,9 +4436,10 @@ 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( @@ -3912,15 +4451,18 @@ 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, @@ -3931,15 +4473,13 @@ 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) @@ -3951,10 +4491,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(): @@ -3962,25 +4502,24 @@ 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, @@ -4000,7 +4539,9 @@ 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) @@ -4014,8 +4555,11 @@ 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: @@ -4029,12 +4573,17 @@ async def test_update_product_async_use_cached_wrapped_rpc(transport: str = "grp 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) @@ -4048,8 +4597,12 @@ async def test_update_product_async_use_cached_wrapped_rpc(transport: str = "grp 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, @@ -4060,16 +4613,16 @@ async def test_update_product_async(transport: str = 'grpc_asyncio', request_typ 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. @@ -4080,16 +4633,17 @@ async def test_update_product_async(transport: str = 'grpc_asyncio', request_typ # 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(), @@ -4099,12 +4653,10 @@ 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) @@ -4116,9 +4668,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 @@ -4131,13 +4683,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. @@ -4148,9 +4700,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(): @@ -4159,16 +4711,14 @@ 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 @@ -4176,10 +4726,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 @@ -4193,10 +4743,11 @@ 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( @@ -4204,18 +4755,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 @@ -4223,12 +4774,13 @@ 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( @@ -4240,16 +4792,19 @@ 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, @@ -4260,9 +4815,7 @@ 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) @@ -4282,28 +4835,29 @@ 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 @@ -4322,7 +4876,9 @@ 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) @@ -4336,8 +4892,11 @@ 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: @@ -4351,12 +4910,17 @@ async def test_delete_product_async_use_cached_wrapped_rpc(transport: str = "grp 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) @@ -4370,8 +4934,12 @@ async def test_delete_product_async_use_cached_wrapped_rpc(transport: str = "grp 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, @@ -4382,9 +4950,7 @@ async def test_delete_product_async(transport: str = 'grpc_asyncio', request_typ 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) @@ -4403,6 +4969,7 @@ async def test_delete_product_async(transport: str = 'grpc_asyncio', request_typ 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(), @@ -4412,12 +4979,10 @@ 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) @@ -4429,9 +4994,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 @@ -4444,12 +5009,10 @@ 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) @@ -4461,9 +5024,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(): @@ -4472,15 +5035,13 @@ 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 @@ -4488,7 +5049,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 @@ -4502,9 +5063,10 @@ 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( @@ -4512,9 +5074,7 @@ 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 @@ -4522,7 +5082,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 @@ -4530,9 +5090,10 @@ 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( @@ -4544,15 +5105,18 @@ 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, @@ -4564,12 +5128,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) @@ -4581,8 +5145,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(): @@ -4590,30 +5154,33 @@ 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 @@ -4628,12 +5195,19 @@ 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) @@ -4646,8 +5220,11 @@ 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: @@ -4661,12 +5238,17 @@ async def test_create_reference_image_async_use_cached_wrapped_rpc(transport: st 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) @@ -4680,8 +5262,12 @@ async def test_create_reference_image_async_use_cached_wrapped_rpc(transport: st 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, @@ -4693,13 +5279,15 @@ async def test_create_reference_image_async(transport: str = 'grpc_asyncio', req # 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. @@ -4710,14 +5298,15 @@ async def test_create_reference_image_async(transport: str = 'grpc_asyncio', req # 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(), @@ -4727,12 +5316,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) @@ -4744,9 +5333,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 @@ -4759,13 +5348,15 @@ 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. @@ -4776,9 +5367,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(): @@ -4788,16 +5379,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 @@ -4805,13 +5396,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 @@ -4825,11 +5416,12 @@ 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( @@ -4838,18 +5430,20 @@ 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 @@ -4857,15 +5451,16 @@ 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( @@ -4877,17 +5472,20 @@ 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, @@ -4899,8 +5497,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) @@ -4920,28 +5518,31 @@ 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 @@ -4956,12 +5557,19 @@ 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) @@ -4974,8 +5582,11 @@ 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: @@ -4989,12 +5600,17 @@ async def test_delete_reference_image_async_use_cached_wrapped_rpc(transport: st 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) @@ -5008,8 +5624,12 @@ async def test_delete_reference_image_async_use_cached_wrapped_rpc(transport: st 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, @@ -5021,8 +5641,8 @@ async def test_delete_reference_image_async(transport: str = 'grpc_asyncio', req # 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) @@ -5041,6 +5661,7 @@ async def test_delete_reference_image_async(transport: str = 'grpc_asyncio', req 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(), @@ -5050,12 +5671,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) @@ -5067,9 +5688,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 @@ -5082,12 +5703,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) @@ -5099,9 +5720,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(): @@ -5111,14 +5732,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 @@ -5126,7 +5747,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 @@ -5140,9 +5761,10 @@ 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( @@ -5151,8 +5773,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 @@ -5160,7 +5782,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 @@ -5168,9 +5790,10 @@ 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( @@ -5182,15 +5805,18 @@ 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, @@ -5202,12 +5828,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) @@ -5220,7 +5846,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(): @@ -5228,30 +5854,33 @@ 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 @@ -5266,12 +5895,19 @@ 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) @@ -5284,8 +5920,11 @@ 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: @@ -5299,12 +5938,17 @@ async def test_list_reference_images_async_use_cached_wrapped_rpc(transport: str 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) @@ -5318,8 +5962,12 @@ async def test_list_reference_images_async_use_cached_wrapped_rpc(transport: str 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, @@ -5331,13 +5979,15 @@ async def test_list_reference_images_async(transport: str = 'grpc_asyncio', requ # 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. @@ -5349,13 +5999,14 @@ async def test_list_reference_images_async(transport: str = 'grpc_asyncio', requ # 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(), @@ -5365,12 +6016,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) @@ -5382,9 +6033,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 @@ -5397,13 +6048,15 @@ 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. @@ -5414,9 +6067,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(): @@ -5426,14 +6079,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 @@ -5441,7 +6094,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 @@ -5455,9 +6108,10 @@ 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( @@ -5466,16 +6120,18 @@ 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 @@ -5483,9 +6139,10 @@ 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( @@ -5497,7 +6154,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", ) @@ -5509,8 +6166,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( @@ -5519,17 +6176,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=[ @@ -5544,9 +6201,7 @@ 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) @@ -5556,8 +6211,11 @@ 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(), @@ -5566,8 +6224,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( @@ -5576,17 +6234,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=[ @@ -5597,9 +6255,10 @@ 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( @@ -5608,8 +6267,10 @@ 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( @@ -5618,17 +6279,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=[ @@ -5638,15 +6299,18 @@ 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 @@ -5657,8 +6321,10 @@ 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( @@ -5667,17 +6333,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=[ @@ -5690,18 +6356,22 @@ 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, @@ -5713,12 +6383,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) @@ -5730,8 +6400,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(): @@ -5739,28 +6409,31 @@ 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 @@ -5775,12 +6448,18 @@ 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) @@ -5793,8 +6472,11 @@ 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: @@ -5808,12 +6490,17 @@ async def test_get_reference_image_async_use_cached_wrapped_rpc(transport: str = 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) @@ -5827,8 +6514,12 @@ async def test_get_reference_image_async_use_cached_wrapped_rpc(transport: str = 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, @@ -5840,13 +6531,15 @@ async def test_get_reference_image_async(transport: str = 'grpc_asyncio', reques # 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. @@ -5857,14 +6550,15 @@ async def test_get_reference_image_async(transport: str = 'grpc_asyncio', reques # 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(), @@ -5874,12 +6568,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) @@ -5891,9 +6585,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 @@ -5906,13 +6600,15 @@ 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. @@ -5923,9 +6619,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(): @@ -5935,14 +6631,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 @@ -5950,7 +6646,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 @@ -5964,9 +6660,10 @@ 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( @@ -5975,16 +6672,18 @@ 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 @@ -5992,9 +6691,10 @@ 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( @@ -6006,15 +6706,18 @@ 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, @@ -6026,8 +6729,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) @@ -6047,30 +6750,33 @@ 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 @@ -6085,12 +6791,19 @@ 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) @@ -6103,8 +6816,11 @@ 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: @@ -6118,12 +6834,17 @@ async def test_add_product_to_product_set_async_use_cached_wrapped_rpc(transport 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) @@ -6137,8 +6858,12 @@ async def test_add_product_to_product_set_async_use_cached_wrapped_rpc(transport 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, @@ -6150,8 +6875,8 @@ async def test_add_product_to_product_set_async(transport: str = 'grpc_asyncio', # 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) @@ -6170,6 +6895,7 @@ async def test_add_product_to_product_set_async(transport: str = 'grpc_asyncio', 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(), @@ -6179,12 +6905,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) @@ -6196,9 +6922,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 @@ -6211,12 +6937,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) @@ -6228,9 +6954,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(): @@ -6240,15 +6966,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 @@ -6256,10 +6982,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 @@ -6273,10 +6999,11 @@ 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( @@ -6285,8 +7012,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 @@ -6294,8 +7021,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 @@ -6303,12 +7030,13 @@ 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( @@ -6320,16 +7048,19 @@ 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, @@ -6341,8 +7072,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) @@ -6362,30 +7093,33 @@ 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 @@ -6400,12 +7134,19 @@ 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) @@ -6418,8 +7159,11 @@ 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: @@ -6433,12 +7177,17 @@ async def test_remove_product_from_product_set_async_use_cached_wrapped_rpc(tran 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) @@ -6452,8 +7201,12 @@ async def test_remove_product_from_product_set_async_use_cached_wrapped_rpc(tran 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, @@ -6465,8 +7218,8 @@ async def test_remove_product_from_product_set_async(transport: str = 'grpc_asyn # 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) @@ -6485,6 +7238,7 @@ async def test_remove_product_from_product_set_async(transport: str = 'grpc_asyn 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(), @@ -6494,12 +7248,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) @@ -6511,9 +7265,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 @@ -6526,12 +7280,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) @@ -6543,9 +7297,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(): @@ -6555,15 +7309,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 @@ -6571,10 +7325,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 @@ -6588,10 +7342,11 @@ 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( @@ -6600,8 +7355,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 @@ -6609,8 +7364,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 @@ -6618,12 +7373,13 @@ 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( @@ -6635,16 +7391,19 @@ 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, @@ -6656,11 +7415,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) @@ -6672,7 +7431,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(): @@ -6680,30 +7439,33 @@ 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 @@ -6718,12 +7480,19 @@ 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) @@ -6736,8 +7505,11 @@ 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: @@ -6751,12 +7523,17 @@ async def test_list_products_in_product_set_async_use_cached_wrapped_rpc(transpo 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) @@ -6770,8 +7547,12 @@ async def test_list_products_in_product_set_async_use_cached_wrapped_rpc(transpo 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, @@ -6783,12 +7564,14 @@ async def test_list_products_in_product_set_async(transport: str = 'grpc_asyncio # 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. @@ -6799,13 +7582,14 @@ async def test_list_products_in_product_set_async(transport: str = 'grpc_asyncio # 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(), @@ -6815,12 +7599,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) @@ -6832,9 +7616,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 @@ -6847,13 +7631,15 @@ 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. @@ -6864,9 +7650,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(): @@ -6876,14 +7662,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 @@ -6891,7 +7677,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 @@ -6905,9 +7691,10 @@ 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( @@ -6916,16 +7703,18 @@ 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 @@ -6933,9 +7722,10 @@ 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( @@ -6947,7 +7737,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", ) @@ -6959,8 +7749,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( @@ -6969,17 +7759,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=[ @@ -6994,11 +7784,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', ''), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", ""),)), + ) + pager = client.list_products_in_product_set( + request={}, retry=retry, timeout=timeout ) - pager = client.list_products_in_product_set(request={}, retry=retry, timeout=timeout) assert pager._metadata == expected_metadata assert pager._retry == retry @@ -7006,8 +7796,9 @@ 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(), @@ -7016,8 +7807,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( @@ -7026,17 +7817,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=[ @@ -7047,9 +7838,10 @@ 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( @@ -7058,8 +7850,10 @@ 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( @@ -7068,17 +7862,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=[ @@ -7088,15 +7882,16 @@ 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 @@ -7107,8 +7902,10 @@ 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( @@ -7117,17 +7914,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=[ @@ -7140,18 +7937,22 @@ 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, @@ -7163,10 +7964,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. @@ -7184,28 +7985,31 @@ 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 @@ -7220,12 +8024,18 @@ 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) @@ -7243,8 +8053,11 @@ 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: @@ -7258,12 +8071,17 @@ async def test_import_product_sets_async_use_cached_wrapped_rpc(transport: str = 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) @@ -7282,8 +8100,12 @@ async def test_import_product_sets_async_use_cached_wrapped_rpc(transport: str = 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, @@ -7295,11 +8117,11 @@ async def test_import_product_sets_async(transport: str = 'grpc_asyncio', reques # 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) @@ -7317,6 +8139,7 @@ async def test_import_product_sets_async(transport: str = 'grpc_asyncio', reques 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(), @@ -7326,13 +8149,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. @@ -7343,9 +8166,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 @@ -7358,13 +8181,15 @@ 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. @@ -7375,9 +8200,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(): @@ -7387,15 +8212,19 @@ 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 @@ -7403,10 +8232,14 @@ 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 @@ -7420,10 +8253,15 @@ 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( @@ -7432,19 +8270,23 @@ 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 @@ -7452,12 +8294,17 @@ 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( @@ -7469,16 +8316,23 @@ 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, @@ -7489,11 +8343,9 @@ 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. @@ -7511,28 +8363,29 @@ 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 @@ -7551,7 +8404,9 @@ 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) @@ -7570,8 +8425,11 @@ 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: @@ -7585,12 +8443,17 @@ async def test_purge_products_async_use_cached_wrapped_rpc(transport: str = "grp 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) @@ -7609,8 +8472,12 @@ async def test_purge_products_async_use_cached_wrapped_rpc(transport: str = "grp 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, @@ -7621,12 +8488,10 @@ async def test_purge_products_async(transport: str = 'grpc_asyncio', request_typ 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) @@ -7644,6 +8509,7 @@ async def test_purge_products_async(transport: str = 'grpc_asyncio', request_typ 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(), @@ -7653,13 +8519,11 @@ 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. @@ -7670,9 +8534,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 @@ -7685,13 +8549,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. @@ -7702,9 +8566,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(): @@ -7713,15 +8577,13 @@ 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 @@ -7729,7 +8591,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 @@ -7743,9 +8605,10 @@ 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( @@ -7753,19 +8616,17 @@ 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 @@ -7773,9 +8634,10 @@ 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( @@ -7787,7 +8649,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", ) @@ -7805,12 +8667,18 @@ 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) @@ -7825,59 +8693,64 @@ 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() @@ -7887,24 +8760,32 @@ def test_create_product_set_rest_required_fields(request_type=product_search_ser 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(): @@ -7914,18 +8795,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) @@ -7935,7 +8816,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"} @@ -7945,10 +8826,14 @@ 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, @@ -7959,9 +8844,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", ) @@ -7983,8 +8868,12 @@ 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) @@ -7999,57 +8888,67 @@ 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 @@ -8057,27 +8956,37 @@ def test_list_product_sets_rest_required_fields(request_type=product_search_serv 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(): @@ -8087,16 +8996,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) @@ -8106,7 +9015,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"} @@ -8116,10 +9025,14 @@ 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, @@ -8130,20 +9043,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( @@ -8152,17 +9065,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=[ @@ -8175,24 +9088,25 @@ 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 @@ -8214,7 +9128,9 @@ 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 = {} @@ -8230,55 +9146,60 @@ 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 @@ -8289,24 +9210,24 @@ def test_get_product_set_rest_required_fields(request_type=product_search_servic 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(): @@ -8316,16 +9237,18 @@ 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) @@ -8335,7 +9258,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"} @@ -8345,10 +9268,14 @@ 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, @@ -8359,7 +9286,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", ) @@ -8377,12 +9304,18 @@ 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) @@ -8397,54 +9330,59 @@ 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() @@ -8454,24 +9392,24 @@ def test_update_product_set_rest_required_fields(request_type=product_search_ser 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(): @@ -8481,17 +9419,21 @@ 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) @@ -8501,7 +9443,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"} @@ -8511,10 +9453,14 @@ 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, @@ -8525,8 +9471,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"]), ) @@ -8544,12 +9490,18 @@ 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) @@ -8564,80 +9516,85 @@ 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(): @@ -8647,24 +9604,26 @@ 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"} @@ -8674,10 +9633,14 @@ 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, @@ -8688,7 +9651,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", ) @@ -8710,7 +9673,9 @@ 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 = {} @@ -8726,59 +9691,64 @@ 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() @@ -8788,24 +9758,32 @@ def test_create_product_rest_required_fields(request_type=product_search_service 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(): @@ -8815,18 +9793,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) @@ -8836,7 +9814,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"} @@ -8846,10 +9824,14 @@ 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, @@ -8860,9 +9842,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", ) @@ -8884,7 +9866,9 @@ 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 = {} @@ -8900,57 +9884,67 @@ 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 @@ -8961,24 +9955,32 @@ def test_list_products_rest_required_fields(request_type=product_search_service. 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(): @@ -8988,16 +9990,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) @@ -9007,7 +10009,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"} @@ -9017,10 +10019,14 @@ 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, @@ -9031,20 +10037,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( @@ -9053,17 +10059,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=[ @@ -9076,24 +10082,25 @@ 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 @@ -9115,7 +10122,9 @@ 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 = {} @@ -9131,55 +10140,60 @@ 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 @@ -9190,24 +10204,24 @@ def test_get_product_rest_required_fields(request_type=product_search_service.Ge 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(): @@ -9217,16 +10231,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) @@ -9236,7 +10250,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"} @@ -9246,10 +10260,14 @@ 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, @@ -9260,7 +10278,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", ) @@ -9282,7 +10300,9 @@ 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 = {} @@ -9298,54 +10318,59 @@ 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() @@ -9355,24 +10380,24 @@ def test_update_product_rest_required_fields(request_type=product_search_service 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(): @@ -9382,17 +10407,19 @@ 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) @@ -9402,7 +10429,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"} @@ -9412,10 +10439,14 @@ 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, @@ -9426,8 +10457,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"]), ) @@ -9449,7 +10480,9 @@ 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 = {} @@ -9465,80 +10498,85 @@ 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(): @@ -9548,24 +10586,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"} @@ -9575,10 +10613,14 @@ 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, @@ -9589,7 +10631,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", ) @@ -9607,12 +10649,19 @@ 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) @@ -9627,59 +10676,64 @@ 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() @@ -9689,24 +10743,32 @@ def test_create_reference_image_rest_required_fields(request_type=product_search 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(): @@ -9716,18 +10778,20 @@ 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) @@ -9737,7 +10801,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"} @@ -9747,10 +10811,14 @@ 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, @@ -9761,9 +10829,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", ) @@ -9781,12 +10849,19 @@ 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) @@ -9801,80 +10876,85 @@ 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(): @@ -9884,24 +10964,26 @@ 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"} @@ -9911,10 +10993,14 @@ 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, @@ -9925,7 +11011,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", ) @@ -9943,12 +11029,19 @@ 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) @@ -9963,57 +11056,67 @@ 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 @@ -10021,27 +11124,37 @@ def test_list_reference_images_rest_required_fields(request_type=product_search_ 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(): @@ -10051,16 +11164,18 @@ 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) @@ -10068,9 +11183,11 @@ 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"} @@ -10080,10 +11197,14 @@ 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, @@ -10094,20 +11215,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( @@ -10116,17 +11237,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=[ @@ -10139,24 +11260,30 @@ 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 @@ -10174,12 +11301,18 @@ 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) @@ -10194,55 +11327,60 @@ 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 @@ -10253,24 +11391,24 @@ def test_get_reference_image_rest_required_fields(request_type=product_search_se 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(): @@ -10280,16 +11418,18 @@ 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) @@ -10299,7 +11439,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"} @@ -10309,10 +11449,14 @@ 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, @@ -10323,7 +11467,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", ) @@ -10341,12 +11485,19 @@ 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) @@ -10361,7 +11512,9 @@ 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 = {} @@ -10369,77 +11522,88 @@ def test_add_product_to_product_set_rest_required_fields(request_type=product_se 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(): @@ -10449,25 +11613,27 @@ 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"} @@ -10477,10 +11643,14 @@ 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, @@ -10491,8 +11661,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", ) @@ -10510,12 +11680,19 @@ 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) @@ -10530,7 +11707,9 @@ 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 = {} @@ -10538,77 +11717,90 @@ def test_remove_product_from_product_set_rest_required_fields(request_type=produ 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(): @@ -10618,25 +11810,27 @@ 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"} @@ -10646,10 +11840,14 @@ 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, @@ -10660,8 +11858,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", ) @@ -10679,12 +11877,19 @@ 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) @@ -10699,57 +11904,67 @@ 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 @@ -10757,27 +11972,37 @@ def test_list_products_in_product_set_rest_required_fields(request_type=product_ 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(): @@ -10787,16 +12012,18 @@ 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) @@ -10804,9 +12031,11 @@ 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"} @@ -10816,10 +12045,14 @@ 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, @@ -10830,20 +12063,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( @@ -10852,17 +12085,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=[ @@ -10875,24 +12108,28 @@ 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 @@ -10910,12 +12147,18 @@ 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) @@ -10934,81 +12177,94 @@ 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(): @@ -11018,17 +12274,21 @@ 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) @@ -11036,7 +12296,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"} @@ -11046,10 +12306,14 @@ 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, @@ -11060,8 +12324,12 @@ 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" + ) + ), ) @@ -11083,7 +12351,9 @@ 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 = {} @@ -11103,81 +12373,86 @@ 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(): @@ -11187,16 +12462,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) @@ -11204,7 +12479,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"} @@ -11214,10 +12489,14 @@ 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, @@ -11228,7 +12507,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", ) @@ -11270,8 +12549,7 @@ 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. @@ -11293,6 +12571,7 @@ 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( @@ -11307,18 +12586,23 @@ 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() @@ -11328,8 +12612,7 @@ 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 @@ -11344,8 +12627,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) @@ -11367,8 +12650,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) @@ -11389,9 +12672,7 @@ 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) @@ -11413,8 +12694,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) @@ -11436,8 +12717,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) @@ -11458,9 +12739,7 @@ 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) @@ -11481,9 +12760,7 @@ 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) @@ -11504,9 +12781,7 @@ 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) @@ -11527,9 +12802,7 @@ 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) @@ -11550,9 +12823,7 @@ 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) @@ -11574,8 +12845,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) @@ -11597,8 +12868,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) @@ -11620,8 +12891,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) @@ -11643,8 +12914,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) @@ -11666,8 +12937,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) @@ -11689,8 +12960,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) @@ -11712,8 +12983,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) @@ -11735,9 +13006,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. @@ -11757,10 +13028,8 @@ 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. @@ -11780,8 +13049,7 @@ 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 @@ -11797,13 +13065,15 @@ 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. @@ -11825,12 +13095,14 @@ 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. @@ -11851,14 +13123,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. @@ -11880,13 +13152,15 @@ 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. @@ -11908,8 +13182,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) @@ -11932,16 +13206,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. @@ -11962,13 +13236,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. @@ -11989,16 +13263,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. @@ -12019,16 +13293,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. @@ -12049,9 +13323,7 @@ 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) @@ -12075,13 +13347,15 @@ 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. @@ -12103,8 +13377,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) @@ -12128,13 +13402,15 @@ 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. @@ -12156,13 +13432,15 @@ 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. @@ -12184,8 +13462,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) @@ -12209,8 +13487,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) @@ -12234,12 +13512,14 @@ 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. @@ -12261,11 +13541,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) @@ -12287,12 +13567,10 @@ 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) @@ -12311,20 +13589,24 @@ 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() @@ -12333,25 +13615,43 @@ def test_create_product_set_rest_bad_request(request_type=product_search_service 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 @@ -12365,7 +13665,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 @@ -12379,7 +13679,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 @@ -12394,12 +13694,16 @@ 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") @@ -12412,11 +13716,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 @@ -12426,34 +13730,47 @@ 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", @@ -12464,11 +13781,13 @@ 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"), ] @@ -12476,27 +13795,37 @@ 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() @@ -12505,25 +13834,27 @@ def test_list_product_sets_rest_bad_request(request_type=product_search_service. 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 @@ -12533,33 +13864,46 @@ 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", @@ -12570,39 +13914,54 @@ 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() @@ -12611,26 +13970,28 @@ def test_get_product_set_rest_bad_request(request_type=product_search_service.Ge 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 @@ -12640,34 +14001,47 @@ 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", @@ -12678,11 +14052,13 @@ 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"), ] @@ -12690,27 +14066,41 @@ 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() @@ -12719,25 +14109,47 @@ def test_update_product_set_rest_bad_request(request_type=product_search_service 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 @@ -12751,7 +14163,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 @@ -12765,7 +14177,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 @@ -12780,12 +14192,16 @@ 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") @@ -12798,11 +14214,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 @@ -12812,34 +14228,47 @@ 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", @@ -12850,11 +14279,13 @@ 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"), ] @@ -12862,27 +14293,37 @@ 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() @@ -12891,30 +14332,32 @@ def test_delete_product_set_rest_bad_request(request_type=product_search_service 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) @@ -12927,15 +14370,23 @@ 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", @@ -12948,31 +14399,41 @@ 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() @@ -12981,19 +14442,27 @@ def test_create_product_rest_bad_request(request_type=product_search_service.Cre 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 @@ -13013,7 +14482,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 @@ -13027,7 +14496,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 @@ -13042,12 +14511,16 @@ 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") @@ -13060,13 +14533,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 @@ -13076,36 +14549,48 @@ 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", @@ -13116,11 +14601,13 @@ 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"), ] @@ -13128,27 +14615,37 @@ 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() @@ -13157,25 +14654,27 @@ def test_list_products_rest_bad_request(request_type=product_search_service.List 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 @@ -13185,33 +14684,45 @@ 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", @@ -13222,39 +14733,54 @@ 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() @@ -13263,28 +14789,30 @@ def test_get_product_rest_bad_request(request_type=product_search_service.GetPro 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 @@ -13294,36 +14822,48 @@ 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", @@ -13334,11 +14874,13 @@ 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"), ] @@ -13346,27 +14888,39 @@ 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() @@ -13375,19 +14929,29 @@ def test_update_product_rest_bad_request(request_type=product_search_service.Upd 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 @@ -13407,7 +14971,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 @@ -13421,7 +14985,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 @@ -13436,12 +15000,16 @@ 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") @@ -13454,13 +15022,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 @@ -13470,36 +15038,48 @@ 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", @@ -13510,11 +15090,13 @@ 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"), ] @@ -13522,27 +15104,37 @@ 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() @@ -13551,30 +15143,32 @@ def test_delete_product_rest_bad_request(request_type=product_search_service.Del 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) @@ -13587,15 +15181,23 @@ 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", @@ -13608,31 +15210,41 @@ 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() @@ -13641,25 +15253,38 @@ def test_create_reference_image_rest_bad_request(request_type=product_search_ser 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 @@ -13673,7 +15298,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 @@ -13687,7 +15312,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 @@ -13702,12 +15327,16 @@ 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") @@ -13720,11 +15349,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 @@ -13734,34 +15363,47 @@ 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", @@ -13772,39 +15414,56 @@ 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() @@ -13813,30 +15472,34 @@ def test_delete_reference_image_rest_bad_request(request_type=product_search_ser 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) @@ -13849,15 +15512,23 @@ 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", @@ -13870,31 +15541,41 @@ 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() @@ -13903,26 +15584,28 @@ def test_list_reference_images_rest_bad_request(request_type=product_search_serv 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 @@ -13930,9 +15613,11 @@ 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) @@ -13940,26 +15625,39 @@ 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", @@ -13970,39 +15668,56 @@ 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() @@ -14011,26 +15726,30 @@ def test_get_reference_image_rest_bad_request(request_type=product_search_servic 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 @@ -14040,34 +15759,47 @@ 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", @@ -14078,39 +15810,54 @@ 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() @@ -14119,30 +15866,32 @@ def test_add_product_to_product_set_rest_bad_request(request_type=product_search 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) @@ -14155,15 +15904,23 @@ 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", @@ -14176,31 +15933,41 @@ 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() @@ -14209,30 +15976,32 @@ def test_remove_product_from_product_set_rest_bad_request(request_type=product_s 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) @@ -14245,15 +16014,24 @@ 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", @@ -14266,31 +16044,41 @@ 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() @@ -14299,25 +16087,27 @@ def test_list_products_in_product_set_rest_bad_request(request_type=product_sear 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 @@ -14325,35 +16115,50 @@ 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", @@ -14364,39 +16169,54 @@ 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() @@ -14405,30 +16225,32 @@ def test_import_product_sets_rest_bad_request(request_type=product_search_servic 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) @@ -14441,20 +16263,33 @@ 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", @@ -14469,7 +16304,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"), ] @@ -14477,27 +16312,37 @@ 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() @@ -14506,30 +16351,32 @@ def test_purge_products_rest_bad_request(request_type=product_search_service.Pur 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) @@ -14542,20 +16389,32 @@ 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", @@ -14570,7 +16429,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"), ] @@ -14578,16 +16437,22 @@ 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 @@ -14602,8 +16467,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. @@ -14624,8 +16489,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. @@ -14645,9 +16510,7 @@ 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. @@ -14668,8 +16531,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. @@ -14690,8 +16553,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. @@ -14711,9 +16574,7 @@ 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. @@ -14733,9 +16594,7 @@ 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. @@ -14755,9 +16614,7 @@ 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. @@ -14777,9 +16634,7 @@ 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. @@ -14799,9 +16654,7 @@ 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. @@ -14822,8 +16675,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. @@ -14844,8 +16697,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. @@ -14866,8 +16719,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. @@ -14888,8 +16741,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. @@ -14910,8 +16763,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. @@ -14932,8 +16785,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. @@ -14954,8 +16807,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. @@ -14976,8 +16829,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. @@ -14997,9 +16850,7 @@ 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. @@ -15020,12 +16871,13 @@ 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( @@ -15036,18 +16888,21 @@ 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(), @@ -15056,25 +16911,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): @@ -15090,7 +16945,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): @@ -15099,26 +16954,39 @@ 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() @@ -15127,15 +16995,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, ) @@ -15150,12 +17018,15 @@ 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", ) @@ -15169,39 +17040,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( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: + 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", @@ -15209,9 +17080,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, @@ -15222,10 +17093,14 @@ 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. @@ -15234,7 +17109,7 @@ def test_product_search_grpc_transport_client_cert_source_for_mtls( 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", @@ -15255,61 +17130,77 @@ def test_product_search_grpc_transport_client_cert_source_for_mtls( 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() @@ -15378,8 +17269,10 @@ 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( @@ -15392,7 +17285,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( @@ -15407,12 +17300,20 @@ 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 @@ -15421,7 +17322,7 @@ def test_product_search_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", @@ -15451,17 +17352,23 @@ def test_product_search_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.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() @@ -15492,7 +17399,7 @@ def test_product_search_transport_channel_mtls_with_adc( def test_product_search_grpc_lro_client(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) transport = client.transport @@ -15509,7 +17416,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 @@ -15527,7 +17434,11 @@ 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 @@ -15544,11 +17455,18 @@ 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 @@ -15565,13 +17483,21 @@ 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 @@ -15588,9 +17514,12 @@ 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 @@ -15605,9 +17534,12 @@ 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 @@ -15622,9 +17554,12 @@ 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 @@ -15639,9 +17574,12 @@ 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 @@ -15656,10 +17594,14 @@ 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 @@ -15679,14 +17621,18 @@ 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(), @@ -15697,10 +17643,11 @@ 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() @@ -15709,10 +17656,11 @@ 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() @@ -15720,10 +17668,11 @@ 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() @@ -15731,13 +17680,12 @@ 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: @@ -15746,10 +17694,14 @@ 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 @@ -15764,7 +17716,9 @@ 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, From a9b4ea917637826a8664de5e275f876c0b0692cc Mon Sep 17 00:00:00 2001 From: ohmayr Date: Wed, 21 Jan 2026 19:43:50 +0000 Subject: [PATCH 3/5] fix import reordering --- .generator/ruff.toml | 14 ++++++++----- .../services/image_annotator/async_client.py | 12 ++++++----- .../services/image_annotator/client.py | 18 +++++++++-------- .../image_annotator/transports/base.py | 11 ++++++---- .../image_annotator/transports/grpc.py | 6 +++--- .../transports/grpc_asyncio.py | 16 +++++++++------ .../image_annotator/transports/rest.py | 15 +++++++++----- .../services/product_search/async_client.py | 12 ++++++----- .../services/product_search/client.py | 18 +++++++++-------- .../services/product_search/pagers.py | 4 +--- .../product_search/transports/base.py | 11 ++++++---- .../product_search/transports/grpc.py | 6 +++--- .../product_search/transports/grpc_asyncio.py | 16 +++++++++------ .../product_search/transports/rest.py | 15 +++++++++----- .../cloud/vision_v1/types/image_annotator.py | 8 ++++++-- .../services/image_annotator/async_client.py | 12 ++++++----- .../services/image_annotator/client.py | 18 +++++++++-------- .../image_annotator/transports/base.py | 6 ++---- .../image_annotator/transports/grpc.py | 6 +++--- .../transports/grpc_asyncio.py | 15 ++++++++------ .../image_annotator/transports/rest.py | 14 ++++++++----- .../vision_v1p1beta1/types/image_annotator.py | 7 +++++-- .../services/image_annotator/async_client.py | 14 +++++++------ .../services/image_annotator/client.py | 20 ++++++++++--------- .../image_annotator/transports/base.py | 11 ++++++---- .../image_annotator/transports/grpc.py | 6 +++--- .../transports/grpc_asyncio.py | 16 +++++++++------ .../image_annotator/transports/rest.py | 15 +++++++++----- .../vision_v1p2beta1/types/image_annotator.py | 7 +++++-- .../services/image_annotator/async_client.py | 12 ++++++----- .../services/image_annotator/client.py | 18 +++++++++-------- .../image_annotator/transports/base.py | 11 ++++++---- .../image_annotator/transports/grpc.py | 6 +++--- .../transports/grpc_asyncio.py | 16 +++++++++------ .../image_annotator/transports/rest.py | 15 +++++++++----- .../services/product_search/async_client.py | 12 ++++++----- .../services/product_search/client.py | 18 +++++++++-------- .../services/product_search/pagers.py | 4 +--- .../product_search/transports/base.py | 11 ++++++---- .../product_search/transports/grpc.py | 6 +++--- .../product_search/transports/grpc_asyncio.py | 16 +++++++++------ .../product_search/transports/rest.py | 15 +++++++++----- .../vision_v1p3beta1/types/image_annotator.py | 2 +- .../services/image_annotator/async_client.py | 12 ++++++----- .../services/image_annotator/client.py | 18 +++++++++-------- .../image_annotator/transports/base.py | 11 ++++++---- .../image_annotator/transports/grpc.py | 6 +++--- .../transports/grpc_asyncio.py | 16 +++++++++------ .../image_annotator/transports/rest.py | 15 +++++++++----- .../services/product_search/async_client.py | 12 ++++++----- .../services/product_search/client.py | 18 +++++++++-------- .../services/product_search/pagers.py | 4 +--- .../product_search/transports/base.py | 11 ++++++---- .../product_search/transports/grpc.py | 6 +++--- .../product_search/transports/grpc_asyncio.py | 16 +++++++++------ .../product_search/transports/rest.py | 15 +++++++++----- .../vision_v1p4beta1/types/image_annotator.py | 2 +- packages/google-cloud-vision/noxfile.py | 2 +- .../gapic/vision_v1/test_image_annotator.py | 10 +++++----- .../gapic/vision_v1/test_product_search.py | 10 +++++----- .../vision_v1p1beta1/test_image_annotator.py | 10 +++++----- .../vision_v1p2beta1/test_image_annotator.py | 10 +++++----- .../vision_v1p3beta1/test_image_annotator.py | 10 +++++----- .../vision_v1p3beta1/test_product_search.py | 10 +++++----- .../vision_v1p4beta1/test_image_annotator.py | 10 +++++----- .../vision_v1p4beta1/test_product_search.py | 10 +++++----- 66 files changed, 442 insertions(+), 313 deletions(-) diff --git a/.generator/ruff.toml b/.generator/ruff.toml index 2aa15ba74c1b..e2adb7bd05d5 100644 --- a/.generator/ruff.toml +++ b/.generator/ruff.toml @@ -1,16 +1,20 @@ # .generator/ruff.toml - -# Match Black's line length line-length = 88 [lint] -# Enable Import sorting (isort) select = ["I"] [lint.isort] -# Force 'google' to be recognized as a first-party import +# 1. Force 'google' to be first-party (keeps google.* imports together) known-first-party = ["google"] +# 2. Combine imports from the same module (Standard isort behavior) +# Prevents splitting "from x import a, b" into multiple lines. +combine-as-imports = true + +# 3. Sort imports by module name, ignoring "from" vs "import" (Standard isort behavior) +# This minimizes diffs where isort mixed them but Ruff separated them. +force-sort-within-sections = true + [format] -# Strictly enforce double quotes (Black style) quote-style = "double" \ No newline at end of file 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 82888d085020..75af779e6c5f 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,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict import logging as std_logging import re -from collections import OrderedDict from typing import ( Callable, Dict, @@ -29,14 +29,16 @@ Union, ) -import google.protobuf -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 import ( + exceptions as core_exceptions, + gapic_v1, + retry_async as retries, +) from google.api_core.client_options import ClientOptions from google.auth import credentials as ga_credentials # type: ignore from google.cloud.vision_v1 import gapic_version as package_version from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] 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 5c41121995a5..93acff20319c 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 @@ -13,13 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict +from http import HTTPStatus import json import logging as std_logging import os import re -import warnings -from collections import OrderedDict -from http import HTTPStatus from typing import ( Callable, Dict, @@ -33,18 +32,21 @@ Union, cast, ) +import warnings -import google.protobuf -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.api_core import ( + client_options as client_options_lib, + exceptions as core_exceptions, + gapic_v1, + 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.cloud.vision_v1 import gapic_version as package_version from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] 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 b3ca63f6ea82..3fc8c39b9508 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 @@ -17,16 +17,19 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import google.api_core +from google.api_core import ( + exceptions as core_exceptions, + gapic_v1, + operations_v1, + retry as retries, +) import google.auth # type: ignore -import google.protobuf -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, operations_v1 -from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore 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 from google.oauth2 import service_account # type: ignore +import google.protobuf DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ 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 9652736cae87..7c866b027d52 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,20 +16,20 @@ import json import logging as std_logging import pickle -import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings import grpc # type: ignore import proto # type: ignore -import google.auth # type: ignore -import google.protobuf.message from google.api_core import gapic_v1, grpc_helpers, operations_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.cloud.vision_v1.types import image_annotator from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson +import google.protobuf.message from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport 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 e2af0b6189ee..00bd9e715fef 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 @@ -17,22 +17,26 @@ import json import logging as std_logging import pickle -import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings import grpc # type: ignore -import proto # type: ignore from grpc.experimental import aio # type: ignore +import proto # type: ignore -import google.protobuf.message -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.api_core import ( + exceptions as core_exceptions, + gapic_v1, + grpc_helpers_async, + operations_v1, + retry_async as retries, +) from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.cloud.vision_v1.types import image_annotator from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson +import google.protobuf.message from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport from .grpc import ImageAnnotatorGrpcTransport 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 2b495669c9f8..83b25e027994 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 @@ -16,19 +16,24 @@ import dataclasses import json # type: ignore import logging -import warnings from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings from requests import __version__ as requests_version -import google.protobuf -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming -from google.api_core import retry as retries +from google.api_core import ( + exceptions as core_exceptions, + gapic_v1, + operations_v1, + rest_helpers, + rest_streaming, + retry as retries, +) from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.requests import AuthorizedSession # type: ignore from google.cloud.vision_v1.types import image_annotator from google.longrunning import operations_pb2 # type: ignore +import google.protobuf from google.protobuf import json_format from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO 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 372b535dd43d..44ca8f9560bd 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,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict import logging as std_logging import re -from collections import OrderedDict from typing import ( Callable, Dict, @@ -29,14 +29,16 @@ Union, ) -import google.protobuf -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 import ( + exceptions as core_exceptions, + gapic_v1, + retry_async as retries, +) from google.api_core.client_options import ClientOptions from google.auth import credentials as ga_credentials # type: ignore from google.cloud.vision_v1 import gapic_version as package_version from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] 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 5f56f98e08a6..74f4f4da37b2 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 @@ -13,13 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict +from http import HTTPStatus import json import logging as std_logging import os import re -import warnings -from collections import OrderedDict -from http import HTTPStatus from typing import ( Callable, Dict, @@ -33,18 +32,21 @@ Union, cast, ) +import warnings -import google.protobuf -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.api_core import ( + client_options as client_options_lib, + exceptions as core_exceptions, + gapic_v1, + 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.cloud.vision_v1 import gapic_version as package_version from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] 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 77727b5abef2..21e7f9e0f7b3 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 @@ -25,9 +25,7 @@ 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 google.api_core import gapic_v1, retry as retries, retry_async as retries_async try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] 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 cd1f1d070427..848b27fb664a 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 @@ -17,16 +17,19 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import google.api_core +from google.api_core import ( + exceptions as core_exceptions, + gapic_v1, + operations_v1, + retry as retries, +) import google.auth # type: ignore -import google.protobuf -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, operations_v1 -from google.api_core import retry as retries from google.auth import credentials as ga_credentials # 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.oauth2 import service_account # type: ignore +import google.protobuf from google.protobuf import empty_pb2 # type: ignore DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 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 51a48068ff4a..30d60daf04b2 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,21 +16,21 @@ import json import logging as std_logging import pickle -import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings import grpc # type: ignore import proto # type: ignore -import google.auth # type: ignore -import google.protobuf.message from google.api_core import gapic_v1, grpc_helpers, operations_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.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.json_format import MessageToJson +import google.protobuf.message from .base import DEFAULT_CLIENT_INFO, ProductSearchTransport 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 b9c12d0229f9..dca5c8f323d4 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 @@ -17,23 +17,27 @@ import json import logging as std_logging import pickle -import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings import grpc # type: ignore -import proto # type: ignore from grpc.experimental import aio # type: ignore +import proto # type: ignore -import google.protobuf.message -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.api_core import ( + exceptions as core_exceptions, + gapic_v1, + grpc_helpers_async, + operations_v1, + retry_async as retries, +) from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.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.json_format import MessageToJson +import google.protobuf.message from .base import DEFAULT_CLIENT_INFO, ProductSearchTransport from .grpc import ProductSearchGrpcTransport 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 aac463001e61..4480ed9376a7 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 @@ -16,19 +16,24 @@ import dataclasses import json # type: ignore import logging -import warnings from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings from requests import __version__ as requests_version -import google.protobuf -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming -from google.api_core import retry as retries +from google.api_core import ( + exceptions as core_exceptions, + gapic_v1, + operations_v1, + rest_helpers, + rest_streaming, + retry as retries, +) from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.requests import AuthorizedSession # type: ignore from google.cloud.vision_v1.types import product_search_service from google.longrunning import operations_pb2 # type: ignore +import google.protobuf from google.protobuf import ( empty_pb2, # type: ignore json_format, 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 f001daa78ca3..223a03d878a5 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 @@ -19,8 +19,12 @@ 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 +from google.cloud.vision_v1.types import ( + geometry, + product_search, + text_annotation, + 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 ( 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 fa34dcaba361..799a51cba00f 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,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict import logging as std_logging import re -from collections import OrderedDict from typing import ( Callable, Dict, @@ -29,14 +29,16 @@ Union, ) -import google.protobuf -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 import ( + exceptions as core_exceptions, + gapic_v1, + retry_async as retries, +) from google.api_core.client_options import ClientOptions from google.auth import credentials as ga_credentials # type: ignore from google.cloud.vision_v1p1beta1 import gapic_version as package_version from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] 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 5c4c76ebb374..f5883928fa1f 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 @@ -13,13 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict +from http import HTTPStatus import json import logging as std_logging import os import re -import warnings -from collections import OrderedDict -from http import HTTPStatus from typing import ( Callable, Dict, @@ -33,18 +32,21 @@ Union, cast, ) +import warnings -import google.protobuf -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.api_core import ( + client_options as client_options_lib, + exceptions as core_exceptions, + gapic_v1, + 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.cloud.vision_v1p1beta1 import gapic_version as package_version from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] 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 e2f38d4464cf..2b2198963dfc 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 @@ -17,15 +17,13 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import google.api_core +from google.api_core import exceptions as core_exceptions, gapic_v1, retry as retries import google.auth # type: ignore -import google.protobuf -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.cloud.vision_v1p1beta1 import gapic_version as package_version from google.cloud.vision_v1p1beta1.types import image_annotator from google.oauth2 import service_account # type: ignore +import google.protobuf DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ 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 c49deb3423bd..be263b789335 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,19 +16,19 @@ import json import logging as std_logging import pickle -import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings import grpc # type: ignore import proto # type: ignore -import google.auth # type: ignore -import google.protobuf.message from google.api_core import gapic_v1, grpc_helpers +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.cloud.vision_v1p1beta1.types import image_annotator from google.protobuf.json_format import MessageToJson +import google.protobuf.message from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport 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 b776a949834b..83e36bc6fba1 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 @@ -17,21 +17,24 @@ import json import logging as std_logging import pickle -import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings import grpc # type: ignore -import proto # type: ignore from grpc.experimental import aio # type: ignore +import proto # type: ignore -import google.protobuf.message -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.api_core import ( + exceptions as core_exceptions, + gapic_v1, + grpc_helpers_async, + retry_async as retries, +) from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.cloud.vision_v1p1beta1.types import image_annotator from google.protobuf.json_format import MessageToJson +import google.protobuf.message from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport from .grpc import ImageAnnotatorGrpcTransport 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 8b9175abb29e..6d01892c8297 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 @@ -16,18 +16,22 @@ import dataclasses import json # type: ignore import logging -import warnings from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings from requests import __version__ as requests_version -import google.protobuf -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.api_core import ( + exceptions as core_exceptions, + gapic_v1, + rest_helpers, + rest_streaming, + retry as retries, +) from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.requests import AuthorizedSession # type: ignore from google.cloud.vision_v1p1beta1.types import image_annotator +import google.protobuf from google.protobuf import json_format from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO 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 1d6547995bfa..23fc5551a93e 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 @@ -19,8 +19,11 @@ import proto # type: ignore -from google.cloud.vision_v1p1beta1.types import geometry, text_annotation -from google.cloud.vision_v1p1beta1.types import web_detection as gcv_web_detection +from google.cloud.vision_v1p1beta1.types import ( + geometry, + text_annotation, + web_detection as gcv_web_detection, +) from google.rpc import status_pb2 # type: ignore from google.type import ( color_pb2, # type: ignore 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 62aec494d909..8d6093e08ead 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,10 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict import logging as std_logging import re -import uuid -from collections import OrderedDict from typing import ( Callable, Dict, @@ -29,15 +28,18 @@ Type, Union, ) +import uuid -import google.protobuf -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 import ( + exceptions as core_exceptions, + gapic_v1, + retry_async as retries, +) from google.api_core.client_options import ClientOptions from google.auth import credentials as ga_credentials # type: ignore from google.cloud.vision_v1p2beta1 import gapic_version as package_version from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] 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 5eb3fe5f92ff..b1688e702763 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 @@ -13,14 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict +from http import HTTPStatus import json import logging as std_logging import os import re -import uuid -import warnings -from collections import OrderedDict -from http import HTTPStatus from typing import ( Callable, Dict, @@ -34,18 +32,22 @@ Union, cast, ) +import uuid +import warnings -import google.protobuf -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.api_core import ( + client_options as client_options_lib, + exceptions as core_exceptions, + gapic_v1, + 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.cloud.vision_v1p2beta1 import gapic_version as package_version from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] 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 f57c0cc890ce..1bc69a9b1fd2 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 @@ -17,16 +17,19 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import google.api_core +from google.api_core import ( + exceptions as core_exceptions, + gapic_v1, + operations_v1, + retry as retries, +) import google.auth # type: ignore -import google.protobuf -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, operations_v1 -from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore 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 from google.oauth2 import service_account # type: ignore +import google.protobuf DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ 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 139314c7cd35..08c15aabb19c 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,20 +16,20 @@ import json import logging as std_logging import pickle -import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings import grpc # type: ignore import proto # type: ignore -import google.auth # type: ignore -import google.protobuf.message from google.api_core import gapic_v1, grpc_helpers, operations_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.cloud.vision_v1p2beta1.types import image_annotator from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson +import google.protobuf.message from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport 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 b8036e5f7625..1fdba766677a 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 @@ -17,22 +17,26 @@ import json import logging as std_logging import pickle -import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings import grpc # type: ignore -import proto # type: ignore from grpc.experimental import aio # type: ignore +import proto # type: ignore -import google.protobuf.message -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.api_core import ( + exceptions as core_exceptions, + gapic_v1, + grpc_helpers_async, + operations_v1, + retry_async as retries, +) from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.cloud.vision_v1p2beta1.types import image_annotator from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson +import google.protobuf.message from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport from .grpc import ImageAnnotatorGrpcTransport 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 d523ab630811..942fa75fe488 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 @@ -16,19 +16,24 @@ import dataclasses import json # type: ignore import logging -import warnings from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings from requests import __version__ as requests_version -import google.protobuf -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming -from google.api_core import retry as retries +from google.api_core import ( + exceptions as core_exceptions, + gapic_v1, + operations_v1, + rest_helpers, + rest_streaming, + retry as retries, +) from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.requests import AuthorizedSession # type: ignore from google.cloud.vision_v1p2beta1.types import image_annotator from google.longrunning import operations_pb2 # type: ignore +import google.protobuf from google.protobuf import json_format from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO 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 d4636a74a300..da2a0ea3fb49 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 @@ -19,8 +19,11 @@ import proto # type: ignore -from google.cloud.vision_v1p2beta1.types import geometry, text_annotation -from google.cloud.vision_v1p2beta1.types import web_detection as gcv_web_detection +from google.cloud.vision_v1p2beta1.types import ( + geometry, + text_annotation, + 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 ( 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 90d2740bb195..15bf7d52ab42 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,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict import logging as std_logging import re -from collections import OrderedDict from typing import ( Callable, Dict, @@ -29,14 +29,16 @@ Union, ) -import google.protobuf -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 import ( + exceptions as core_exceptions, + gapic_v1, + retry_async as retries, +) from google.api_core.client_options import ClientOptions from google.auth import credentials as ga_credentials # type: ignore from google.cloud.vision_v1p3beta1 import gapic_version as package_version from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] 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 ce9fae8f7992..462acb262d44 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 @@ -13,13 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict +from http import HTTPStatus import json import logging as std_logging import os import re -import warnings -from collections import OrderedDict -from http import HTTPStatus from typing import ( Callable, Dict, @@ -33,18 +32,21 @@ Union, cast, ) +import warnings -import google.protobuf -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.api_core import ( + client_options as client_options_lib, + exceptions as core_exceptions, + gapic_v1, + 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.cloud.vision_v1p3beta1 import gapic_version as package_version from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] 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 7019358b6e55..128bd120a285 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 @@ -17,16 +17,19 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import google.api_core +from google.api_core import ( + exceptions as core_exceptions, + gapic_v1, + operations_v1, + retry as retries, +) import google.auth # type: ignore -import google.protobuf -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, operations_v1 -from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore 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 from google.oauth2 import service_account # type: ignore +import google.protobuf DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ 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 cd2e279de727..77ae562b649d 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,20 +16,20 @@ import json import logging as std_logging import pickle -import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings import grpc # type: ignore import proto # type: ignore -import google.auth # type: ignore -import google.protobuf.message from google.api_core import gapic_v1, grpc_helpers, operations_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.cloud.vision_v1p3beta1.types import image_annotator from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson +import google.protobuf.message from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport 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 9a2e2c8a7d0c..bb6ad86f1ab5 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 @@ -17,22 +17,26 @@ import json import logging as std_logging import pickle -import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings import grpc # type: ignore -import proto # type: ignore from grpc.experimental import aio # type: ignore +import proto # type: ignore -import google.protobuf.message -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.api_core import ( + exceptions as core_exceptions, + gapic_v1, + grpc_helpers_async, + operations_v1, + retry_async as retries, +) from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.cloud.vision_v1p3beta1.types import image_annotator from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson +import google.protobuf.message from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport from .grpc import ImageAnnotatorGrpcTransport 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 110f3c387a2f..79f47a3436ed 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 @@ -16,19 +16,24 @@ import dataclasses import json # type: ignore import logging -import warnings from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings from requests import __version__ as requests_version -import google.protobuf -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming -from google.api_core import retry as retries +from google.api_core import ( + exceptions as core_exceptions, + gapic_v1, + operations_v1, + rest_helpers, + rest_streaming, + retry as retries, +) from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.requests import AuthorizedSession # type: ignore from google.cloud.vision_v1p3beta1.types import image_annotator from google.longrunning import operations_pb2 # type: ignore +import google.protobuf from google.protobuf import json_format from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO 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 43b5ad311964..015b06040c26 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,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict import logging as std_logging import re -from collections import OrderedDict from typing import ( Callable, Dict, @@ -29,14 +29,16 @@ Union, ) -import google.protobuf -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 import ( + exceptions as core_exceptions, + gapic_v1, + retry_async as retries, +) from google.api_core.client_options import ClientOptions from google.auth import credentials as ga_credentials # type: ignore from google.cloud.vision_v1p3beta1 import gapic_version as package_version from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] 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 1bc7f8efcfdf..89ba0939e5fc 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 @@ -13,13 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict +from http import HTTPStatus import json import logging as std_logging import os import re -import warnings -from collections import OrderedDict -from http import HTTPStatus from typing import ( Callable, Dict, @@ -33,18 +32,21 @@ Union, cast, ) +import warnings -import google.protobuf -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.api_core import ( + client_options as client_options_lib, + exceptions as core_exceptions, + gapic_v1, + 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.cloud.vision_v1p3beta1 import gapic_version as package_version from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] 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 9913867a51ff..ead863e7b042 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 @@ -25,9 +25,7 @@ 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 google.api_core import gapic_v1, retry as retries, retry_async as retries_async try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] 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 d14337a52fe4..cd86b3fd2fc4 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 @@ -17,16 +17,19 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import google.api_core +from google.api_core import ( + exceptions as core_exceptions, + gapic_v1, + operations_v1, + retry as retries, +) import google.auth # type: ignore -import google.protobuf -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, operations_v1 -from google.api_core import retry as retries from google.auth import credentials as ga_credentials # 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.oauth2 import service_account # type: ignore +import google.protobuf from google.protobuf import empty_pb2 # type: ignore DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 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 fe5991cb78b3..87d631b5e4c7 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,21 +16,21 @@ import json import logging as std_logging import pickle -import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings import grpc # type: ignore import proto # type: ignore -import google.auth # type: ignore -import google.protobuf.message from google.api_core import gapic_v1, grpc_helpers, operations_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.cloud.vision_v1p3beta1.types import product_search_service 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 from .base import DEFAULT_CLIENT_INFO, ProductSearchTransport 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 bec18a4fc85f..a59932b9b040 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 @@ -17,23 +17,27 @@ import json import logging as std_logging import pickle -import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings import grpc # type: ignore -import proto # type: ignore from grpc.experimental import aio # type: ignore +import proto # type: ignore -import google.protobuf.message -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.api_core import ( + exceptions as core_exceptions, + gapic_v1, + grpc_helpers_async, + operations_v1, + retry_async as retries, +) from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.cloud.vision_v1p3beta1.types import product_search_service 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 from .base import DEFAULT_CLIENT_INFO, ProductSearchTransport from .grpc import ProductSearchGrpcTransport 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 058c73a504f0..c2a24acf440a 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 @@ -16,19 +16,24 @@ import dataclasses import json # type: ignore import logging -import warnings from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings from requests import __version__ as requests_version -import google.protobuf -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming -from google.api_core import retry as retries +from google.api_core import ( + exceptions as core_exceptions, + gapic_v1, + operations_v1, + rest_helpers, + rest_streaming, + retry as retries, +) from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.requests import AuthorizedSession # type: ignore from google.cloud.vision_v1p3beta1.types import product_search_service from google.longrunning import operations_pb2 # type: ignore +import google.protobuf from google.protobuf import ( empty_pb2, # type: ignore json_format, 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 6d3f2dece1ed..b131e3c79d58 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 @@ -23,8 +23,8 @@ geometry, product_search, text_annotation, + web_detection as gcv_web_detection, ) -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 ( 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 f11ac646d8af..83dfce6f05fb 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,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict import logging as std_logging import re -from collections import OrderedDict from typing import ( Callable, Dict, @@ -29,14 +29,16 @@ Union, ) -import google.protobuf -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 import ( + exceptions as core_exceptions, + gapic_v1, + retry_async as retries, +) from google.api_core.client_options import ClientOptions from google.auth import credentials as ga_credentials # type: ignore from google.cloud.vision_v1p4beta1 import gapic_version as package_version from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] 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 5a49828ed9a5..da561c0aa36a 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 @@ -13,13 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict +from http import HTTPStatus import json import logging as std_logging import os import re -import warnings -from collections import OrderedDict -from http import HTTPStatus from typing import ( Callable, Dict, @@ -33,18 +32,21 @@ Union, cast, ) +import warnings -import google.protobuf -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.api_core import ( + client_options as client_options_lib, + exceptions as core_exceptions, + gapic_v1, + 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.cloud.vision_v1p4beta1 import gapic_version as package_version from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] 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 12ea8f92c5cc..736dc63f6157 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 @@ -17,16 +17,19 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import google.api_core +from google.api_core import ( + exceptions as core_exceptions, + gapic_v1, + operations_v1, + retry as retries, +) import google.auth # type: ignore -import google.protobuf -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, operations_v1 -from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore 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 from google.oauth2 import service_account # type: ignore +import google.protobuf DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ 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 2ad4223f8a4f..f50053756e77 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,20 +16,20 @@ import json import logging as std_logging import pickle -import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings import grpc # type: ignore import proto # type: ignore -import google.auth # type: ignore -import google.protobuf.message from google.api_core import gapic_v1, grpc_helpers, operations_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.cloud.vision_v1p4beta1.types import image_annotator from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson +import google.protobuf.message from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport 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 28d4ccb13beb..415575fa6c9f 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 @@ -17,22 +17,26 @@ import json import logging as std_logging import pickle -import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings import grpc # type: ignore -import proto # type: ignore from grpc.experimental import aio # type: ignore +import proto # type: ignore -import google.protobuf.message -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.api_core import ( + exceptions as core_exceptions, + gapic_v1, + grpc_helpers_async, + operations_v1, + retry_async as retries, +) from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.cloud.vision_v1p4beta1.types import image_annotator from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson +import google.protobuf.message from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport from .grpc import ImageAnnotatorGrpcTransport 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 912b670267a3..d0d3a4ea1a83 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 @@ -16,19 +16,24 @@ import dataclasses import json # type: ignore import logging -import warnings from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings from requests import __version__ as requests_version -import google.protobuf -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming -from google.api_core import retry as retries +from google.api_core import ( + exceptions as core_exceptions, + gapic_v1, + operations_v1, + rest_helpers, + rest_streaming, + retry as retries, +) from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.requests import AuthorizedSession # type: ignore from google.cloud.vision_v1p4beta1.types import image_annotator from google.longrunning import operations_pb2 # type: ignore +import google.protobuf from google.protobuf import json_format from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO 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 18e2b301a048..c1fd10da923b 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,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict import logging as std_logging import re -from collections import OrderedDict from typing import ( Callable, Dict, @@ -29,14 +29,16 @@ Union, ) -import google.protobuf -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 import ( + exceptions as core_exceptions, + gapic_v1, + retry_async as retries, +) from google.api_core.client_options import ClientOptions from google.auth import credentials as ga_credentials # type: ignore from google.cloud.vision_v1p4beta1 import gapic_version as package_version from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] 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 93ec3da47c75..fdb56a27ea4e 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 @@ -13,13 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict +from http import HTTPStatus import json import logging as std_logging import os import re -import warnings -from collections import OrderedDict -from http import HTTPStatus from typing import ( Callable, Dict, @@ -33,18 +32,21 @@ Union, cast, ) +import warnings -import google.protobuf -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.api_core import ( + client_options as client_options_lib, + exceptions as core_exceptions, + gapic_v1, + 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.cloud.vision_v1p4beta1 import gapic_version as package_version from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] 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 d6d1065fd30d..3748d92defa5 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 @@ -25,9 +25,7 @@ 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 google.api_core import gapic_v1, retry as retries, retry_async as retries_async try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] 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 9e018b77fcb2..8127e41f9141 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 @@ -17,16 +17,19 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import google.api_core +from google.api_core import ( + exceptions as core_exceptions, + gapic_v1, + operations_v1, + retry as retries, +) import google.auth # type: ignore -import google.protobuf -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, operations_v1 -from google.api_core import retry as retries from google.auth import credentials as ga_credentials # 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.oauth2 import service_account # type: ignore +import google.protobuf from google.protobuf import empty_pb2 # type: ignore DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 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 7b4a484917ae..ced4ceb0defc 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,21 +16,21 @@ import json import logging as std_logging import pickle -import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings import grpc # type: ignore import proto # type: ignore -import google.auth # type: ignore -import google.protobuf.message from google.api_core import gapic_v1, grpc_helpers, operations_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.cloud.vision_v1p4beta1.types import product_search_service 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 from .base import DEFAULT_CLIENT_INFO, ProductSearchTransport 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 53e56434d0c8..c2db0e58479b 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 @@ -17,23 +17,27 @@ import json import logging as std_logging import pickle -import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings import grpc # type: ignore -import proto # type: ignore from grpc.experimental import aio # type: ignore +import proto # type: ignore -import google.protobuf.message -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.api_core import ( + exceptions as core_exceptions, + gapic_v1, + grpc_helpers_async, + operations_v1, + retry_async as retries, +) from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.cloud.vision_v1p4beta1.types import product_search_service 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 from .base import DEFAULT_CLIENT_INFO, ProductSearchTransport from .grpc import ProductSearchGrpcTransport 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 fc05036bec73..4f80555feb65 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 @@ -16,19 +16,24 @@ import dataclasses import json # type: ignore import logging -import warnings from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings from requests import __version__ as requests_version -import google.protobuf -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming -from google.api_core import retry as retries +from google.api_core import ( + exceptions as core_exceptions, + gapic_v1, + operations_v1, + rest_helpers, + rest_streaming, + retry as retries, +) from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.requests import AuthorizedSession # type: ignore from google.cloud.vision_v1p4beta1.types import product_search_service from google.longrunning import operations_pb2 # type: ignore +import google.protobuf from google.protobuf import ( empty_pb2, # type: ignore json_format, 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 9cc6e4e05e7b..15809df3bb2e 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 @@ -24,8 +24,8 @@ geometry, product_search, text_annotation, + web_detection as gcv_web_detection, ) -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 ( diff --git a/packages/google-cloud-vision/noxfile.py b/packages/google-cloud-vision/noxfile.py index b68cc9fa8ccc..59ceb95f779f 100644 --- a/packages/google-cloud-vision/noxfile.py +++ b/packages/google-cloud-vision/noxfile.py @@ -17,8 +17,8 @@ import pathlib import re import shutil -import warnings from typing import Dict, List +import warnings import nox 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 6cd7eeb113bd..de4b102458a9 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 @@ -22,15 +22,15 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import AsyncIterable, Iterable import json import math -from collections.abc import AsyncIterable, Iterable import grpc -import pytest from grpc.experimental import aio from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest from requests import PreparedRequest, Request, Response from requests.sessions import Session @@ -44,9 +44,9 @@ except ImportError: # pragma: NO COVER HAS_GOOGLE_AUTH_AIO = False -import google.auth from google.api_core import ( client_options, + exceptions as core_exceptions, future, gapic_v1, grpc_helpers, @@ -55,9 +55,9 @@ operation_async, # type: ignore operations_v1, path_template, + retry as retries, ) -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries +import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.vision_v1.services.image_annotator import ( 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 710705ee4cbc..9a6e08a83ceb 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 @@ -22,15 +22,15 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import AsyncIterable, Iterable import json import math -from collections.abc import AsyncIterable, Iterable import grpc -import pytest from grpc.experimental import aio from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest from requests import PreparedRequest, Request, Response from requests.sessions import Session @@ -44,9 +44,9 @@ except ImportError: # pragma: NO COVER HAS_GOOGLE_AUTH_AIO = False -import google.auth from google.api_core import ( client_options, + exceptions as core_exceptions, future, gapic_v1, grpc_helpers, @@ -55,9 +55,9 @@ operation_async, # type: ignore operations_v1, path_template, + retry as retries, ) -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries +import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.vision_v1.services.product_search import ( 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 c2d2bd88b483..f1a0134d4d7c 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 @@ -22,15 +22,15 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import AsyncIterable, Iterable import json import math -from collections.abc import AsyncIterable, Iterable import grpc -import pytest from grpc.experimental import aio from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest from requests import PreparedRequest, Request, Response from requests.sessions import Session @@ -44,16 +44,16 @@ except ImportError: # pragma: NO COVER HAS_GOOGLE_AUTH_AIO = False -import google.auth from google.api_core import ( client_options, + exceptions as core_exceptions, gapic_v1, grpc_helpers, grpc_helpers_async, path_template, + retry as retries, ) -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries +import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.vision_v1p1beta1.services.image_annotator import ( 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 3378b6867a3c..78931afeeaf5 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 @@ -23,15 +23,15 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import AsyncIterable, Iterable import json import math -from collections.abc import AsyncIterable, Iterable import grpc -import pytest from grpc.experimental import aio from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest from requests import PreparedRequest, Request, Response from requests.sessions import Session @@ -45,9 +45,9 @@ except ImportError: # pragma: NO COVER HAS_GOOGLE_AUTH_AIO = False -import google.auth from google.api_core import ( client_options, + exceptions as core_exceptions, future, gapic_v1, grpc_helpers, @@ -56,9 +56,9 @@ operation_async, # type: ignore operations_v1, path_template, + retry as retries, ) -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries +import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.vision_v1p2beta1.services.image_annotator import ( 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 3ee75983a5fc..48d88ecf4ad3 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 @@ -22,15 +22,15 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import AsyncIterable, Iterable import json import math -from collections.abc import AsyncIterable, Iterable import grpc -import pytest from grpc.experimental import aio from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest from requests import PreparedRequest, Request, Response from requests.sessions import Session @@ -44,9 +44,9 @@ except ImportError: # pragma: NO COVER HAS_GOOGLE_AUTH_AIO = False -import google.auth from google.api_core import ( client_options, + exceptions as core_exceptions, future, gapic_v1, grpc_helpers, @@ -55,9 +55,9 @@ operation_async, # type: ignore operations_v1, path_template, + retry as retries, ) -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries +import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.vision_v1p3beta1.services.image_annotator import ( 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 ceb825065a7e..3e3475ce587e 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 @@ -22,15 +22,15 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import AsyncIterable, Iterable import json import math -from collections.abc import AsyncIterable, Iterable import grpc -import pytest from grpc.experimental import aio from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest from requests import PreparedRequest, Request, Response from requests.sessions import Session @@ -44,9 +44,9 @@ except ImportError: # pragma: NO COVER HAS_GOOGLE_AUTH_AIO = False -import google.auth from google.api_core import ( client_options, + exceptions as core_exceptions, future, gapic_v1, grpc_helpers, @@ -55,9 +55,9 @@ operation_async, # type: ignore operations_v1, path_template, + retry as retries, ) -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries +import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.vision_v1p3beta1.services.product_search import ( 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 6396bb4b7f9a..ef856a6372f9 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 @@ -22,15 +22,15 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import AsyncIterable, Iterable import json import math -from collections.abc import AsyncIterable, Iterable import grpc -import pytest from grpc.experimental import aio from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest from requests import PreparedRequest, Request, Response from requests.sessions import Session @@ -44,9 +44,9 @@ except ImportError: # pragma: NO COVER HAS_GOOGLE_AUTH_AIO = False -import google.auth from google.api_core import ( client_options, + exceptions as core_exceptions, future, gapic_v1, grpc_helpers, @@ -55,9 +55,9 @@ operation_async, # type: ignore operations_v1, path_template, + retry as retries, ) -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries +import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.vision_v1p4beta1.services.image_annotator import ( 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 8e5e9d41995e..9d67584fb969 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 @@ -22,15 +22,15 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import AsyncIterable, Iterable import json import math -from collections.abc import AsyncIterable, Iterable import grpc -import pytest from grpc.experimental import aio from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest from requests import PreparedRequest, Request, Response from requests.sessions import Session @@ -44,9 +44,9 @@ except ImportError: # pragma: NO COVER HAS_GOOGLE_AUTH_AIO = False -import google.auth from google.api_core import ( client_options, + exceptions as core_exceptions, future, gapic_v1, grpc_helpers, @@ -55,9 +55,9 @@ operation_async, # type: ignore operations_v1, path_template, + retry as retries, ) -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries +import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.vision_v1p4beta1.services.product_search import ( From faaf31f28236c1c57858d0bf4c64d422b8a99b7e Mon Sep 17 00:00:00 2001 From: ohmayr Date: Wed, 21 Jan 2026 19:52:31 +0000 Subject: [PATCH 4/5] disable known first party --- .generator/ruff.toml | 4 +- .../image_annotator/transports/grpc.py | 5 +- .../transports/grpc_asyncio.py | 7 +- .../image_annotator/transports/rest.py | 8 +- .../services/product_search/async_client.py | 12 +- .../services/product_search/client.py | 12 +- .../product_search/transports/grpc.py | 5 +- .../product_search/transports/grpc_asyncio.py | 7 +- .../product_search/transports/rest.py | 23 +- .../cloud/vision_v1/types/image_annotator.py | 3 +- .../cloud/vision_v1/types/product_search.py | 3 +- .../vision_v1/types/product_search_service.py | 3 +- .../cloud/vision_v1/types/text_annotation.py | 3 +- .../image_annotator/transports/grpc.py | 5 +- .../transports/grpc_asyncio.py | 7 +- .../image_annotator/transports/rest.py | 4 +- .../vision_v1p1beta1/types/image_annotator.py | 3 +- .../vision_v1p1beta1/types/text_annotation.py | 3 +- .../image_annotator/transports/grpc.py | 5 +- .../transports/grpc_asyncio.py | 7 +- .../image_annotator/transports/rest.py | 5 +- .../vision_v1p2beta1/types/image_annotator.py | 3 +- .../vision_v1p2beta1/types/text_annotation.py | 3 +- .../image_annotator/transports/grpc.py | 5 +- .../transports/grpc_asyncio.py | 7 +- .../image_annotator/transports/rest.py | 5 +- .../services/product_search/async_client.py | 12 +- .../services/product_search/client.py | 12 +- .../product_search/transports/grpc.py | 5 +- .../product_search/transports/grpc_asyncio.py | 7 +- .../product_search/transports/rest.py | 21 +- .../vision_v1p3beta1/types/image_annotator.py | 3 +- .../vision_v1p3beta1/types/product_search.py | 3 +- .../types/product_search_service.py | 3 +- .../vision_v1p3beta1/types/text_annotation.py | 3 +- .../image_annotator/transports/grpc.py | 5 +- .../transports/grpc_asyncio.py | 7 +- .../image_annotator/transports/rest.py | 7 +- .../services/product_search/async_client.py | 12 +- .../services/product_search/client.py | 12 +- .../product_search/transports/grpc.py | 5 +- .../product_search/transports/grpc_asyncio.py | 7 +- .../product_search/transports/rest.py | 22 +- .../vision_v1p4beta1/types/image_annotator.py | 3 +- .../vision_v1p4beta1/types/product_search.py | 3 +- .../types/product_search_service.py | 3 +- .../vision_v1p4beta1/types/text_annotation.py | 3 +- .../gapic/vision_v1/test_image_annotator.py | 15 +- .../gapic/vision_v1/test_product_search.py | 209 +++++++----------- .../vision_v1p1beta1/test_image_annotator.py | 5 +- .../vision_v1p2beta1/test_image_annotator.py | 5 +- .../vision_v1p3beta1/test_image_annotator.py | 5 +- .../vision_v1p3beta1/test_product_search.py | 209 +++++++----------- .../vision_v1p4beta1/test_image_annotator.py | 15 +- .../vision_v1p4beta1/test_product_search.py | 209 +++++++----------- 55 files changed, 447 insertions(+), 540 deletions(-) diff --git a/.generator/ruff.toml b/.generator/ruff.toml index e2adb7bd05d5..bc875505b412 100644 --- a/.generator/ruff.toml +++ b/.generator/ruff.toml @@ -1,12 +1,14 @@ # .generator/ruff.toml line-length = 88 +# Enable preview to get the strictest Black compatibility +preview = true [lint] select = ["I"] [lint.isort] # 1. Force 'google' to be first-party (keeps google.* imports together) -known-first-party = ["google"] +# known-first-party = ["google"] # 2. Combine imports from the same module (Standard isort behavior) # Prevents splitting "from x import a, b" into multiple lines. 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 7c866b027d52..f0ba9e980442 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 @@ -19,9 +19,6 @@ from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings -import grpc # type: ignore -import proto # type: ignore - from google.api_core import gapic_v1, grpc_helpers, operations_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore @@ -30,6 +27,8 @@ 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 .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport 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 00bd9e715fef..60710eea1439 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 @@ -20,10 +20,6 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings -import grpc # type: ignore -from grpc.experimental import aio # type: ignore -import proto # type: ignore - from google.api_core import ( exceptions as core_exceptions, gapic_v1, @@ -37,6 +33,9 @@ from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message +import grpc # type: ignore +from grpc.experimental import aio # type: ignore +import proto # type: ignore from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport from .grpc import ImageAnnotatorGrpcTransport 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 83b25e027994..274e851970fd 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 @@ -19,8 +19,6 @@ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from requests import __version__ as requests_version - from google.api_core import ( exceptions as core_exceptions, gapic_v1, @@ -35,6 +33,7 @@ from google.longrunning import operations_pb2 # type: ignore import google.protobuf from google.protobuf import json_format +from requests import __version__ as requests_version from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO from .rest_base import _BaseImageAnnotatorRestTransport @@ -498,6 +497,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -655,6 +655,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -810,6 +811,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -964,6 +966,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -1169,6 +1172,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) 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 44ca8f9560bd..9376fe31ecec 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 @@ -841,9 +841,9 @@ async 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. @@ -1476,9 +1476,9 @@ async 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. 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 74f4f4da37b2..034a1928419e 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 @@ -1303,9 +1303,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. @@ -1923,9 +1923,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. 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 30d60daf04b2..ef3db3247967 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 @@ -19,9 +19,6 @@ from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings -import grpc # type: ignore -import proto # type: ignore - from google.api_core import gapic_v1, grpc_helpers, operations_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore @@ -31,6 +28,8 @@ 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 .base import DEFAULT_CLIENT_INFO, ProductSearchTransport 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 dca5c8f323d4..58212cf89dc9 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 @@ -20,10 +20,6 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings -import grpc # type: ignore -from grpc.experimental import aio # type: ignore -import proto # type: ignore - from google.api_core import ( exceptions as core_exceptions, gapic_v1, @@ -38,6 +34,9 @@ from google.protobuf import empty_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message +import grpc # type: ignore +from grpc.experimental import aio # type: ignore +import proto # type: ignore from .base import DEFAULT_CLIENT_INFO, ProductSearchTransport from .grpc import ProductSearchGrpcTransport 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 4480ed9376a7..426da4762a11 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 @@ -19,8 +19,6 @@ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from requests import __version__ as requests_version - from google.api_core import ( exceptions as core_exceptions, gapic_v1, @@ -38,6 +36,7 @@ empty_pb2, # type: ignore json_format, ) +from requests import __version__ as requests_version from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO from .rest_base import _BaseProductSearchRestTransport @@ -1196,6 +1195,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -1310,6 +1310,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -1460,6 +1461,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -1617,6 +1619,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -1771,6 +1774,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -1877,6 +1881,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -1983,6 +1988,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -2089,6 +2095,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -2237,6 +2244,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -2388,6 +2396,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -2536,6 +2545,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -2687,6 +2697,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -2833,6 +2844,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -2982,6 +2994,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -3136,6 +3149,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -3284,6 +3298,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -3436,6 +3451,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -3552,6 +3568,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -3702,6 +3719,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -4063,6 +4081,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) 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 223a03d878a5..a5a9a80e648a 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,8 +17,6 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.cloud.vision_v1.types import ( geometry, product_search, @@ -31,6 +29,7 @@ color_pb2, # type: ignore latlng_pb2, # type: ignore ) +import proto # type: ignore __protobuf__ = proto.module( package="google.cloud.vision.v1", 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 f0299458bc05..a39a9e866dad 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,10 +17,9 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.cloud.vision_v1.types import geometry, product_search_service from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore __protobuf__ = proto.module( package="google.cloud.vision.v1", 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 71c64951e4e2..0db0301c1e4b 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,14 +17,13 @@ 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 timestamp_pb2, # type: ignore ) from google.rpc import status_pb2 # type: ignore +import proto # type: ignore __protobuf__ = proto.module( package="google.cloud.vision.v1", 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 59a288e308a1..dddd0807d9ca 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 @@ -17,9 +17,8 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.cloud.vision_v1.types import geometry +import proto # type: ignore __protobuf__ = proto.module( package="google.cloud.vision.v1", 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 be263b789335..338caf4ee85e 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 @@ -19,9 +19,6 @@ from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings -import grpc # type: ignore -import proto # type: ignore - from google.api_core import gapic_v1, grpc_helpers import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore @@ -29,6 +26,8 @@ from google.cloud.vision_v1p1beta1.types import image_annotator from google.protobuf.json_format import MessageToJson import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport 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 83e36bc6fba1..67ed5de0b2b6 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 @@ -20,10 +20,6 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings -import grpc # type: ignore -from grpc.experimental import aio # type: ignore -import proto # type: ignore - from google.api_core import ( exceptions as core_exceptions, gapic_v1, @@ -35,6 +31,9 @@ from google.cloud.vision_v1p1beta1.types import image_annotator from google.protobuf.json_format import MessageToJson import google.protobuf.message +import grpc # type: ignore +from grpc.experimental import aio # type: ignore +import proto # type: ignore from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport from .grpc import ImageAnnotatorGrpcTransport 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 6d01892c8297..952a63d2adb1 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 @@ -19,8 +19,6 @@ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from requests import __version__ as requests_version - from google.api_core import ( exceptions as core_exceptions, gapic_v1, @@ -33,6 +31,7 @@ from google.cloud.vision_v1p1beta1.types import image_annotator import google.protobuf from google.protobuf import json_format +from requests import __version__ as requests_version from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO from .rest_base import _BaseImageAnnotatorRestTransport @@ -250,6 +249,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) 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 23fc5551a93e..48b5103bbfd8 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,8 +17,6 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.cloud.vision_v1p1beta1.types import ( geometry, text_annotation, @@ -29,6 +27,7 @@ color_pb2, # type: ignore latlng_pb2, # type: ignore ) +import proto # type: ignore __protobuf__ = proto.module( package="google.cloud.vision.v1p1beta1", 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 a419cae40f21..722c919433de 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 @@ -17,9 +17,8 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.cloud.vision_v1p1beta1.types import geometry +import proto # type: ignore __protobuf__ = proto.module( package="google.cloud.vision.v1p1beta1", 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 08c15aabb19c..c14911e3a9d2 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 @@ -19,9 +19,6 @@ from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings -import grpc # type: ignore -import proto # type: ignore - from google.api_core import gapic_v1, grpc_helpers, operations_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore @@ -30,6 +27,8 @@ 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 .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport 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 1fdba766677a..965edb9418fa 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 @@ -20,10 +20,6 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings -import grpc # type: ignore -from grpc.experimental import aio # type: ignore -import proto # type: ignore - from google.api_core import ( exceptions as core_exceptions, gapic_v1, @@ -37,6 +33,9 @@ from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message +import grpc # type: ignore +from grpc.experimental import aio # type: ignore +import proto # type: ignore from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport from .grpc import ImageAnnotatorGrpcTransport 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 942fa75fe488..35ce5fc63dc5 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 @@ -19,8 +19,6 @@ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from requests import __version__ as requests_version - from google.api_core import ( exceptions as core_exceptions, gapic_v1, @@ -35,6 +33,7 @@ from google.longrunning import operations_pb2 # type: ignore import google.protobuf from google.protobuf import json_format +from requests import __version__ as requests_version from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO from .rest_base import _BaseImageAnnotatorRestTransport @@ -337,6 +336,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -494,6 +494,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) 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 da2a0ea3fb49..62deae4d4b00 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,8 +17,6 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.cloud.vision_v1p2beta1.types import ( geometry, text_annotation, @@ -30,6 +28,7 @@ color_pb2, # type: ignore latlng_pb2, # type: ignore ) +import proto # type: ignore __protobuf__ = proto.module( package="google.cloud.vision.v1p2beta1", 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 b9d25b950022..53181f8b3e0a 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 @@ -17,9 +17,8 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.cloud.vision_v1p2beta1.types import geometry +import proto # type: ignore __protobuf__ = proto.module( package="google.cloud.vision.v1p2beta1", 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 77ae562b649d..741e8d60035b 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 @@ -19,9 +19,6 @@ from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings -import grpc # type: ignore -import proto # type: ignore - from google.api_core import gapic_v1, grpc_helpers, operations_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore @@ -30,6 +27,8 @@ 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 .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport 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 bb6ad86f1ab5..ba1f798e163c 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 @@ -20,10 +20,6 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings -import grpc # type: ignore -from grpc.experimental import aio # type: ignore -import proto # type: ignore - from google.api_core import ( exceptions as core_exceptions, gapic_v1, @@ -37,6 +33,9 @@ from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message +import grpc # type: ignore +from grpc.experimental import aio # type: ignore +import proto # type: ignore from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport from .grpc import ImageAnnotatorGrpcTransport 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 79f47a3436ed..0a427962974a 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 @@ -19,8 +19,6 @@ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from requests import __version__ as requests_version - from google.api_core import ( exceptions as core_exceptions, gapic_v1, @@ -35,6 +33,7 @@ from google.longrunning import operations_pb2 # type: ignore import google.protobuf from google.protobuf import json_format +from requests import __version__ as requests_version from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO from .rest_base import _BaseImageAnnotatorRestTransport @@ -337,6 +336,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -494,6 +494,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) 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 015b06040c26..5fbf7d714bbd 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 @@ -841,9 +841,9 @@ async 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. @@ -1480,9 +1480,9 @@ async 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. 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 89ba0939e5fc..64f764ce0616 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 @@ -1303,9 +1303,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. @@ -1927,9 +1927,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. 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 87d631b5e4c7..ff3bbf8d8591 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 @@ -19,9 +19,6 @@ from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings -import grpc # type: ignore -import proto # type: ignore - from google.api_core import gapic_v1, grpc_helpers, operations_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore @@ -31,6 +28,8 @@ 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 .base import DEFAULT_CLIENT_INFO, ProductSearchTransport 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 a59932b9b040..bda008538473 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 @@ -20,10 +20,6 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings -import grpc # type: ignore -from grpc.experimental import aio # type: ignore -import proto # type: ignore - from google.api_core import ( exceptions as core_exceptions, gapic_v1, @@ -38,6 +34,9 @@ from google.protobuf import empty_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message +import grpc # type: ignore +from grpc.experimental import aio # type: ignore +import proto # type: ignore from .base import DEFAULT_CLIENT_INFO, ProductSearchTransport from .grpc import ProductSearchGrpcTransport 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 c2a24acf440a..21ae4406ad0f 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 @@ -19,8 +19,6 @@ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from requests import __version__ as requests_version - from google.api_core import ( exceptions as core_exceptions, gapic_v1, @@ -38,6 +36,7 @@ empty_pb2, # type: ignore json_format, ) +from requests import __version__ as requests_version from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO from .rest_base import _BaseProductSearchRestTransport @@ -1097,6 +1096,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -1211,6 +1211,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -1361,6 +1362,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -1518,6 +1520,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -1672,6 +1675,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -1778,6 +1782,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -1884,6 +1889,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -1990,6 +1996,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -2138,6 +2145,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -2289,6 +2297,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -2437,6 +2446,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -2588,6 +2598,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -2734,6 +2745,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -2883,6 +2895,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -3037,6 +3050,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -3186,6 +3200,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -3302,6 +3317,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -3452,6 +3468,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) 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 b131e3c79d58..7d48a396f249 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,8 +17,6 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.cloud.vision_v1p3beta1.types import ( geometry, product_search, @@ -31,6 +29,7 @@ color_pb2, # type: ignore latlng_pb2, # type: ignore ) +import proto # type: ignore __protobuf__ = proto.module( package="google.cloud.vision.v1p3beta1", 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 3d8dbbdf5d34..940086c9ab9d 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,10 +17,9 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.cloud.vision_v1p3beta1.types import geometry, product_search_service from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore __protobuf__ = proto.module( package="google.cloud.vision.v1p3beta1", 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 bd9cd32c2815..f9a7b5ec2c2e 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,14 +17,13 @@ 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 timestamp_pb2, # type: ignore ) from google.rpc import status_pb2 # type: ignore +import proto # type: ignore __protobuf__ = proto.module( package="google.cloud.vision.v1p3beta1", 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 ad12e61d4254..4d30a350308b 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 @@ -17,9 +17,8 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.cloud.vision_v1p3beta1.types import geometry +import proto # type: ignore __protobuf__ = proto.module( package="google.cloud.vision.v1p3beta1", 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 f50053756e77..2bdc92e3464e 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 @@ -19,9 +19,6 @@ from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings -import grpc # type: ignore -import proto # type: ignore - from google.api_core import gapic_v1, grpc_helpers, operations_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore @@ -30,6 +27,8 @@ 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 .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport 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 415575fa6c9f..76566ceb1b60 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 @@ -20,10 +20,6 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings -import grpc # type: ignore -from grpc.experimental import aio # type: ignore -import proto # type: ignore - from google.api_core import ( exceptions as core_exceptions, gapic_v1, @@ -37,6 +33,9 @@ from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message +import grpc # type: ignore +from grpc.experimental import aio # type: ignore +import proto # type: ignore from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport from .grpc import ImageAnnotatorGrpcTransport 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 d0d3a4ea1a83..1b11f25fac41 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 @@ -19,8 +19,6 @@ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from requests import __version__ as requests_version - from google.api_core import ( exceptions as core_exceptions, gapic_v1, @@ -35,6 +33,7 @@ from google.longrunning import operations_pb2 # type: ignore import google.protobuf from google.protobuf import json_format +from requests import __version__ as requests_version from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO from .rest_base import _BaseImageAnnotatorRestTransport @@ -454,6 +453,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -611,6 +611,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -766,6 +767,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -920,6 +922,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) 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 c1fd10da923b..37f64945dba0 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 @@ -842,9 +842,9 @@ async 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. @@ -1477,9 +1477,9 @@ async 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. 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 fdb56a27ea4e..52d42bca02f3 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 @@ -1304,9 +1304,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. @@ -1924,9 +1924,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. 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 ced4ceb0defc..e7dfba14abf4 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 @@ -19,9 +19,6 @@ from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings -import grpc # type: ignore -import proto # type: ignore - from google.api_core import gapic_v1, grpc_helpers, operations_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore @@ -31,6 +28,8 @@ 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 .base import DEFAULT_CLIENT_INFO, ProductSearchTransport 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 c2db0e58479b..42715e1e4c19 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 @@ -20,10 +20,6 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings -import grpc # type: ignore -from grpc.experimental import aio # type: ignore -import proto # type: ignore - from google.api_core import ( exceptions as core_exceptions, gapic_v1, @@ -38,6 +34,9 @@ from google.protobuf import empty_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message +import grpc # type: ignore +from grpc.experimental import aio # type: ignore +import proto # type: ignore from .base import DEFAULT_CLIENT_INFO, ProductSearchTransport from .grpc import ProductSearchGrpcTransport 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 4f80555feb65..c203412eb20a 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 @@ -19,8 +19,6 @@ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from requests import __version__ as requests_version - from google.api_core import ( exceptions as core_exceptions, gapic_v1, @@ -38,6 +36,7 @@ empty_pb2, # type: ignore json_format, ) +from requests import __version__ as requests_version from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO from .rest_base import _BaseProductSearchRestTransport @@ -1154,6 +1153,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -1268,6 +1268,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -1418,6 +1419,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -1575,6 +1577,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -1729,6 +1732,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -1835,6 +1839,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -1941,6 +1946,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -2047,6 +2053,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -2195,6 +2202,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -2346,6 +2354,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -2494,6 +2503,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -2645,6 +2655,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -2791,6 +2802,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -2940,6 +2952,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -3094,6 +3107,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -3242,6 +3256,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -3394,6 +3409,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -3510,6 +3526,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) @@ -3660,6 +3677,7 @@ def _get_response( transcoded_request, body=None, ): + uri = transcoded_request["uri"] method = transcoded_request["method"] headers = dict(metadata) 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 15809df3bb2e..73f89b3fe35e 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,8 +17,6 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.cloud.vision_v1p4beta1.types import ( face, geometry, @@ -32,6 +30,7 @@ color_pb2, # type: ignore latlng_pb2, # type: ignore ) +import proto # type: ignore __protobuf__ = proto.module( package="google.cloud.vision.v1p4beta1", 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 20b3ddf17961..0767a7ed9db2 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,10 +17,9 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.cloud.vision_v1p4beta1.types import geometry, product_search_service from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore __protobuf__ = proto.module( package="google.cloud.vision.v1p4beta1", 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 af4c368eb0db..e308f576527f 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,14 +17,13 @@ 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 timestamp_pb2, # type: ignore ) from google.rpc import status_pb2 # type: ignore +import proto # type: ignore __protobuf__ = proto.module( package="google.cloud.vision.v1p4beta1", 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 0eccb1718213..a49d2e7319f2 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 @@ -17,9 +17,8 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.cloud.vision_v1p4beta1.types import geometry +import proto # type: ignore __protobuf__ = proto.module( package="google.cloud.vision.v1p4beta1", 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 de4b102458a9..e4b54134cdfa 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 @@ -26,6 +26,8 @@ import json import math +from google.api_core import api_core_version +from google.protobuf import json_format import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers @@ -34,9 +36,6 @@ from requests import PreparedRequest, Request, Response from requests.sessions import Session -from google.api_core import api_core_version -from google.protobuf import json_format - try: from google.auth.aio import credentials as ga_credentials_async @@ -3059,12 +3058,10 @@ def test_async_batch_annotate_images_rest_unset_required_fields(): unset_fields = transport.async_batch_annotate_images._get_unset_required_fields({}) assert set(unset_fields) == ( set(()) - & set( - ( - "requests", - "outputConfig", - ) - ) + & set(( + "requests", + "outputConfig", + )) ) 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 9a6e08a83ceb..090890c91213 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 @@ -26,6 +26,8 @@ import json import math +from google.api_core import api_core_version +from google.protobuf import json_format import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers @@ -34,9 +36,6 @@ from requests import PreparedRequest, Request, Response from requests.sessions import Session -from google.api_core import api_core_version -from google.protobuf import json_format - try: from google.auth.aio import credentials as ga_credentials_async @@ -8779,12 +8778,10 @@ def test_create_product_set_rest_unset_required_fields(): unset_fields = transport.create_product_set._get_unset_required_fields({}) assert set(unset_fields) == ( set(("productSetId",)) - & set( - ( - "parent", - "productSet", - ) - ) + & set(( + "parent", + "productSet", + )) ) @@ -8916,12 +8913,10 @@ def test_list_product_sets_rest_required_fields( 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 @@ -8979,12 +8974,10 @@ def test_list_product_sets_rest_unset_required_fields(): unset_fields = transport.list_product_sets._get_unset_required_fields({}) assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) + set(( + "pageSize", + "pageToken", + )) & set(("parent",)) ) @@ -9777,12 +9770,10 @@ def test_create_product_rest_unset_required_fields(): unset_fields = transport.create_product._get_unset_required_fields({}) assert set(unset_fields) == ( set(("productId",)) - & set( - ( - "parent", - "product", - ) - ) + & set(( + "parent", + "product", + )) ) @@ -9911,12 +9902,10 @@ def test_list_products_rest_required_fields( 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 @@ -9972,12 +9961,10 @@ def test_list_products_rest_unset_required_fields(): unset_fields = transport.list_products._get_unset_required_fields({}) assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) + set(( + "pageSize", + "pageToken", + )) & set(("parent",)) ) @@ -10758,12 +10745,10 @@ def test_create_reference_image_rest_unset_required_fields(): unset_fields = transport.create_reference_image._get_unset_required_fields({}) assert set(unset_fields) == ( set(("referenceImageId",)) - & set( - ( - "parent", - "referenceImage", - ) - ) + & set(( + "parent", + "referenceImage", + )) ) @@ -11080,12 +11065,10 @@ def test_list_reference_images_rest_required_fields( 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 @@ -11143,12 +11126,10 @@ def test_list_reference_images_rest_unset_required_fields(): unset_fields = transport.list_reference_images._get_unset_required_fields({}) assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) + set(( + "pageSize", + "pageToken", + )) & set(("parent",)) ) @@ -11593,12 +11574,10 @@ def test_add_product_to_product_set_rest_unset_required_fields(): unset_fields = transport.add_product_to_product_set._get_unset_required_fields({}) assert set(unset_fields) == ( set(()) - & set( - ( - "name", - "product", - ) - ) + & set(( + "name", + "product", + )) ) @@ -11785,17 +11764,15 @@ def test_remove_product_from_product_set_rest_unset_required_fields(): credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.remove_product_from_product_set._get_unset_required_fields( - {} + unset_fields = ( + transport.remove_product_from_product_set._get_unset_required_fields({}) ) assert set(unset_fields) == ( set(()) - & set( - ( - "name", - "product", - ) - ) + & set(( + "name", + "product", + )) ) @@ -11928,12 +11905,10 @@ def test_list_products_in_product_set_rest_required_fields( 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 @@ -11991,12 +11966,10 @@ def test_list_products_in_product_set_rest_unset_required_fields(): unset_fields = transport.list_products_in_product_set._get_unset_required_fields({}) assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) + set(( + "pageSize", + "pageToken", + )) & set(("name",)) ) @@ -12254,12 +12227,10 @@ def test_import_product_sets_rest_unset_required_fields(): unset_fields = transport.import_product_sets._get_unset_required_fields({}) assert set(unset_fields) == ( set(()) - & set( - ( - "parent", - "inputConfig", - ) - ) + & set(( + "parent", + "inputConfig", + )) ) @@ -13689,13 +13660,11 @@ def get_message_fields(field): if result and hasattr(result, "keys"): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) + subfields_not_in_runtime.append({ + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + }) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime @@ -14187,13 +14156,11 @@ def get_message_fields(field): if result and hasattr(result, "keys"): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) + subfields_not_in_runtime.append({ + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + }) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime @@ -14506,13 +14473,11 @@ def get_message_fields(field): if result and hasattr(result, "keys"): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) + subfields_not_in_runtime.append({ + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + }) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime @@ -14995,13 +14960,11 @@ def get_message_fields(field): if result and hasattr(result, "keys"): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) + subfields_not_in_runtime.append({ + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + }) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime @@ -15322,13 +15285,11 @@ def get_message_fields(field): if result and hasattr(result, "keys"): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) + subfields_not_in_runtime.append({ + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + }) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime 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 f1a0134d4d7c..19ca8958e6c7 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 @@ -26,6 +26,8 @@ import json import math +from google.api_core import api_core_version +from google.protobuf import json_format import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers @@ -34,9 +36,6 @@ from requests import PreparedRequest, Request, Response from requests.sessions import Session -from google.api_core import api_core_version -from google.protobuf import json_format - try: from google.auth.aio import credentials as ga_credentials_async 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 78931afeeaf5..2f36e9882594 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 @@ -27,6 +27,8 @@ import json import math +from google.api_core import api_core_version +from google.protobuf import json_format import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers @@ -35,9 +37,6 @@ from requests import PreparedRequest, Request, Response from requests.sessions import Session -from google.api_core import api_core_version -from google.protobuf import json_format - try: from google.auth.aio import credentials as ga_credentials_async 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 48d88ecf4ad3..d65744bbd313 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 @@ -26,6 +26,8 @@ import json import math +from google.api_core import api_core_version +from google.protobuf import json_format import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers @@ -34,9 +36,6 @@ from requests import PreparedRequest, Request, Response from requests.sessions import Session -from google.api_core import api_core_version -from google.protobuf import json_format - try: from google.auth.aio import credentials as ga_credentials_async 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 3e3475ce587e..14b15fb0178e 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 @@ -26,6 +26,8 @@ import json import math +from google.api_core import api_core_version +from google.protobuf import json_format import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers @@ -34,9 +36,6 @@ from requests import PreparedRequest, Request, Response from requests.sessions import Session -from google.api_core import api_core_version -from google.protobuf import json_format - try: from google.auth.aio import credentials as ga_credentials_async @@ -8450,12 +8449,10 @@ def test_create_product_set_rest_unset_required_fields(): unset_fields = transport.create_product_set._get_unset_required_fields({}) assert set(unset_fields) == ( set(("productSetId",)) - & set( - ( - "parent", - "productSet", - ) - ) + & set(( + "parent", + "productSet", + )) ) @@ -8587,12 +8584,10 @@ def test_list_product_sets_rest_required_fields( 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 @@ -8650,12 +8645,10 @@ def test_list_product_sets_rest_unset_required_fields(): unset_fields = transport.list_product_sets._get_unset_required_fields({}) assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) + set(( + "pageSize", + "pageToken", + )) & set(("parent",)) ) @@ -9448,12 +9441,10 @@ def test_create_product_rest_unset_required_fields(): unset_fields = transport.create_product._get_unset_required_fields({}) assert set(unset_fields) == ( set(("productId",)) - & set( - ( - "parent", - "product", - ) - ) + & set(( + "parent", + "product", + )) ) @@ -9583,12 +9574,10 @@ def test_list_products_rest_required_fields( 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 @@ -9644,12 +9633,10 @@ def test_list_products_rest_unset_required_fields(): unset_fields = transport.list_products._get_unset_required_fields({}) assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) + set(( + "pageSize", + "pageToken", + )) & set(("parent",)) ) @@ -10433,12 +10420,10 @@ def test_create_reference_image_rest_unset_required_fields(): unset_fields = transport.create_reference_image._get_unset_required_fields({}) assert set(unset_fields) == ( set(("referenceImageId",)) - & set( - ( - "parent", - "referenceImage", - ) - ) + & set(( + "parent", + "referenceImage", + )) ) @@ -10755,12 +10740,10 @@ def test_list_reference_images_rest_required_fields( 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 @@ -10818,12 +10801,10 @@ def test_list_reference_images_rest_unset_required_fields(): unset_fields = transport.list_reference_images._get_unset_required_fields({}) assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) + set(( + "pageSize", + "pageToken", + )) & set(("parent",)) ) @@ -11268,12 +11249,10 @@ def test_add_product_to_product_set_rest_unset_required_fields(): unset_fields = transport.add_product_to_product_set._get_unset_required_fields({}) assert set(unset_fields) == ( set(()) - & set( - ( - "name", - "product", - ) - ) + & set(( + "name", + "product", + )) ) @@ -11460,17 +11439,15 @@ def test_remove_product_from_product_set_rest_unset_required_fields(): credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.remove_product_from_product_set._get_unset_required_fields( - {} + unset_fields = ( + transport.remove_product_from_product_set._get_unset_required_fields({}) ) assert set(unset_fields) == ( set(()) - & set( - ( - "name", - "product", - ) - ) + & set(( + "name", + "product", + )) ) @@ -11603,12 +11580,10 @@ def test_list_products_in_product_set_rest_required_fields( 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 @@ -11666,12 +11641,10 @@ def test_list_products_in_product_set_rest_unset_required_fields(): unset_fields = transport.list_products_in_product_set._get_unset_required_fields({}) assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) + set(( + "pageSize", + "pageToken", + )) & set(("name",)) ) @@ -11929,12 +11902,10 @@ def test_import_product_sets_rest_unset_required_fields(): unset_fields = transport.import_product_sets._get_unset_required_fields({}) assert set(unset_fields) == ( set(()) - & set( - ( - "parent", - "inputConfig", - ) - ) + & set(( + "parent", + "inputConfig", + )) ) @@ -13140,13 +13111,11 @@ def get_message_fields(field): if result and hasattr(result, "keys"): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) + subfields_not_in_runtime.append({ + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + }) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime @@ -13638,13 +13607,11 @@ def get_message_fields(field): if result and hasattr(result, "keys"): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) + subfields_not_in_runtime.append({ + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + }) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime @@ -13957,13 +13924,11 @@ def get_message_fields(field): if result and hasattr(result, "keys"): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) + subfields_not_in_runtime.append({ + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + }) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime @@ -14446,13 +14411,11 @@ def get_message_fields(field): if result and hasattr(result, "keys"): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) + subfields_not_in_runtime.append({ + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + }) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime @@ -14773,13 +14736,11 @@ def get_message_fields(field): if result and hasattr(result, "keys"): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) + subfields_not_in_runtime.append({ + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + }) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime 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 ef856a6372f9..7f463ae50442 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 @@ -26,6 +26,8 @@ import json import math +from google.api_core import api_core_version +from google.protobuf import json_format import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers @@ -34,9 +36,6 @@ from requests import PreparedRequest, Request, Response from requests.sessions import Session -from google.api_core import api_core_version -from google.protobuf import json_format - try: from google.auth.aio import credentials as ga_credentials_async @@ -3048,12 +3047,10 @@ def test_async_batch_annotate_images_rest_unset_required_fields(): unset_fields = transport.async_batch_annotate_images._get_unset_required_fields({}) assert set(unset_fields) == ( set(()) - & set( - ( - "requests", - "outputConfig", - ) - ) + & set(( + "requests", + "outputConfig", + )) ) 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 9d67584fb969..9b16a039d1d6 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 @@ -26,6 +26,8 @@ import json import math +from google.api_core import api_core_version +from google.protobuf import json_format import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers @@ -34,9 +36,6 @@ from requests import PreparedRequest, Request, Response from requests.sessions import Session -from google.api_core import api_core_version -from google.protobuf import json_format - try: from google.auth.aio import credentials as ga_credentials_async @@ -8779,12 +8778,10 @@ def test_create_product_set_rest_unset_required_fields(): unset_fields = transport.create_product_set._get_unset_required_fields({}) assert set(unset_fields) == ( set(("productSetId",)) - & set( - ( - "parent", - "productSet", - ) - ) + & set(( + "parent", + "productSet", + )) ) @@ -8916,12 +8913,10 @@ def test_list_product_sets_rest_required_fields( 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 @@ -8979,12 +8974,10 @@ def test_list_product_sets_rest_unset_required_fields(): unset_fields = transport.list_product_sets._get_unset_required_fields({}) assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) + set(( + "pageSize", + "pageToken", + )) & set(("parent",)) ) @@ -9777,12 +9770,10 @@ def test_create_product_rest_unset_required_fields(): unset_fields = transport.create_product._get_unset_required_fields({}) assert set(unset_fields) == ( set(("productId",)) - & set( - ( - "parent", - "product", - ) - ) + & set(( + "parent", + "product", + )) ) @@ -9912,12 +9903,10 @@ def test_list_products_rest_required_fields( 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 @@ -9973,12 +9962,10 @@ def test_list_products_rest_unset_required_fields(): unset_fields = transport.list_products._get_unset_required_fields({}) assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) + set(( + "pageSize", + "pageToken", + )) & set(("parent",)) ) @@ -10762,12 +10749,10 @@ def test_create_reference_image_rest_unset_required_fields(): unset_fields = transport.create_reference_image._get_unset_required_fields({}) assert set(unset_fields) == ( set(("referenceImageId",)) - & set( - ( - "parent", - "referenceImage", - ) - ) + & set(( + "parent", + "referenceImage", + )) ) @@ -11084,12 +11069,10 @@ def test_list_reference_images_rest_required_fields( 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 @@ -11147,12 +11130,10 @@ def test_list_reference_images_rest_unset_required_fields(): unset_fields = transport.list_reference_images._get_unset_required_fields({}) assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) + set(( + "pageSize", + "pageToken", + )) & set(("parent",)) ) @@ -11597,12 +11578,10 @@ def test_add_product_to_product_set_rest_unset_required_fields(): unset_fields = transport.add_product_to_product_set._get_unset_required_fields({}) assert set(unset_fields) == ( set(()) - & set( - ( - "name", - "product", - ) - ) + & set(( + "name", + "product", + )) ) @@ -11789,17 +11768,15 @@ def test_remove_product_from_product_set_rest_unset_required_fields(): credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.remove_product_from_product_set._get_unset_required_fields( - {} + unset_fields = ( + transport.remove_product_from_product_set._get_unset_required_fields({}) ) assert set(unset_fields) == ( set(()) - & set( - ( - "name", - "product", - ) - ) + & set(( + "name", + "product", + )) ) @@ -11932,12 +11909,10 @@ def test_list_products_in_product_set_rest_required_fields( 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 @@ -11995,12 +11970,10 @@ def test_list_products_in_product_set_rest_unset_required_fields(): unset_fields = transport.list_products_in_product_set._get_unset_required_fields({}) assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) + set(( + "pageSize", + "pageToken", + )) & set(("name",)) ) @@ -12258,12 +12231,10 @@ def test_import_product_sets_rest_unset_required_fields(): unset_fields = transport.import_product_sets._get_unset_required_fields({}) assert set(unset_fields) == ( set(()) - & set( - ( - "parent", - "inputConfig", - ) - ) + & set(( + "parent", + "inputConfig", + )) ) @@ -13693,13 +13664,11 @@ def get_message_fields(field): if result and hasattr(result, "keys"): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) + subfields_not_in_runtime.append({ + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + }) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime @@ -14191,13 +14160,11 @@ def get_message_fields(field): if result and hasattr(result, "keys"): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) + subfields_not_in_runtime.append({ + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + }) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime @@ -14510,13 +14477,11 @@ def get_message_fields(field): if result and hasattr(result, "keys"): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) + subfields_not_in_runtime.append({ + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + }) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime @@ -14999,13 +14964,11 @@ def get_message_fields(field): if result and hasattr(result, "keys"): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) + subfields_not_in_runtime.append({ + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + }) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime @@ -15326,13 +15289,11 @@ def get_message_fields(field): if result and hasattr(result, "keys"): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) + subfields_not_in_runtime.append({ + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + }) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime From b65713e6fa39f047a8f22a60278ddd661be5373a Mon Sep 17 00:00:00 2001 From: ohmayr Date: Wed, 21 Jan 2026 19:55:24 +0000 Subject: [PATCH 5/5] disable combine as imports --- .generator/ruff.toml | 2 +- .../services/image_annotator/async_client.py | 8 +++----- .../vision_v1/services/image_annotator/client.py | 10 ++++------ .../services/image_annotator/transports/base.py | 9 +++------ .../image_annotator/transports/grpc_asyncio.py | 10 +++------- .../services/image_annotator/transports/rest.py | 11 +++-------- .../vision_v1/services/product_search/async_client.py | 8 +++----- .../cloud/vision_v1/services/product_search/client.py | 10 ++++------ .../cloud/vision_v1/services/product_search/pagers.py | 4 +++- .../services/product_search/transports/base.py | 9 +++------ .../product_search/transports/grpc_asyncio.py | 10 +++------- .../services/product_search/transports/rest.py | 11 +++-------- .../google/cloud/vision_v1/types/image_annotator.py | 8 ++------ .../services/image_annotator/async_client.py | 8 +++----- .../services/image_annotator/client.py | 10 ++++------ .../services/image_annotator/transports/base.py | 4 +++- .../image_annotator/transports/grpc_asyncio.py | 9 +++------ .../services/image_annotator/transports/rest.py | 10 +++------- .../cloud/vision_v1p1beta1/types/image_annotator.py | 7 ++----- .../services/image_annotator/async_client.py | 8 +++----- .../services/image_annotator/client.py | 10 ++++------ .../services/image_annotator/transports/base.py | 9 +++------ .../image_annotator/transports/grpc_asyncio.py | 10 +++------- .../services/image_annotator/transports/rest.py | 11 +++-------- .../cloud/vision_v1p2beta1/types/image_annotator.py | 7 ++----- .../services/image_annotator/async_client.py | 8 +++----- .../services/image_annotator/client.py | 10 ++++------ .../services/image_annotator/transports/base.py | 9 +++------ .../image_annotator/transports/grpc_asyncio.py | 10 +++------- .../services/image_annotator/transports/rest.py | 11 +++-------- .../services/product_search/async_client.py | 8 +++----- .../services/product_search/client.py | 10 ++++------ .../services/product_search/pagers.py | 4 +++- .../services/product_search/transports/base.py | 9 +++------ .../product_search/transports/grpc_asyncio.py | 10 +++------- .../services/product_search/transports/rest.py | 11 +++-------- .../cloud/vision_v1p3beta1/types/image_annotator.py | 2 +- .../services/image_annotator/async_client.py | 8 +++----- .../services/image_annotator/client.py | 10 ++++------ .../services/image_annotator/transports/base.py | 9 +++------ .../image_annotator/transports/grpc_asyncio.py | 10 +++------- .../services/image_annotator/transports/rest.py | 11 +++-------- .../services/product_search/async_client.py | 8 +++----- .../services/product_search/client.py | 10 ++++------ .../services/product_search/pagers.py | 4 +++- .../services/product_search/transports/base.py | 9 +++------ .../product_search/transports/grpc_asyncio.py | 10 +++------- .../services/product_search/transports/rest.py | 11 +++-------- .../cloud/vision_v1p4beta1/types/image_annotator.py | 2 +- .../unit/gapic/vision_v1/test_image_annotator.py | 4 ++-- .../tests/unit/gapic/vision_v1/test_product_search.py | 4 ++-- .../gapic/vision_v1p1beta1/test_image_annotator.py | 4 ++-- .../gapic/vision_v1p2beta1/test_image_annotator.py | 4 ++-- .../gapic/vision_v1p3beta1/test_image_annotator.py | 4 ++-- .../gapic/vision_v1p3beta1/test_product_search.py | 4 ++-- .../gapic/vision_v1p4beta1/test_image_annotator.py | 4 ++-- .../gapic/vision_v1p4beta1/test_product_search.py | 4 ++-- 57 files changed, 162 insertions(+), 287 deletions(-) diff --git a/.generator/ruff.toml b/.generator/ruff.toml index bc875505b412..3983fe43ac2e 100644 --- a/.generator/ruff.toml +++ b/.generator/ruff.toml @@ -12,7 +12,7 @@ select = ["I"] # 2. Combine imports from the same module (Standard isort behavior) # Prevents splitting "from x import a, b" into multiple lines. -combine-as-imports = true +# combine-as-imports = true # 3. Sort imports by module name, ignoring "from" vs "import" (Standard isort behavior) # This minimizes diffs where isort mixed them but Ruff separated them. 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 75af779e6c5f..e1ccc9c08f1d 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 @@ -29,11 +29,9 @@ Union, ) -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - retry_async as retries, -) +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.cloud.vision_v1 import gapic_version as package_version 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 93acff20319c..41cba6fd7478 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 @@ -34,12 +34,10 @@ ) import warnings -from google.api_core import ( - client_options as client_options_lib, - exceptions as core_exceptions, - gapic_v1, - retry as retries, -) +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 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 3fc8c39b9508..c899fee5886f 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 @@ -17,12 +17,9 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import google.api_core -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - operations_v1, - retry as retries, -) +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_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.cloud.vision_v1 import gapic_version as package_version 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 60710eea1439..37c1428091fe 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 @@ -20,13 +20,9 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - grpc_helpers_async, - operations_v1, - retry_async as retries, -) +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.auth.transport.grpc import SslCredentials # type: ignore from google.cloud.vision_v1.types import image_annotator 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 274e851970fd..a1ae05ec3d49 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 @@ -19,14 +19,9 @@ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - operations_v1, - rest_helpers, - rest_streaming, - retry as retries, -) +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_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.cloud.vision_v1.types import image_annotator 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 9376fe31ecec..bc64b6c301bb 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 @@ -29,11 +29,9 @@ Union, ) -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - retry_async as retries, -) +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.cloud.vision_v1 import gapic_version as package_version 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 034a1928419e..a9abb43c5bf1 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 @@ -34,12 +34,10 @@ ) import warnings -from google.api_core import ( - client_options as client_options_lib, - exceptions as core_exceptions, - gapic_v1, - retry as retries, -) +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 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 21e7f9e0f7b3..77727b5abef2 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 @@ -25,7 +25,9 @@ Union, ) -from google.api_core import gapic_v1, retry as retries, retry_async as retries_async +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] 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 848b27fb664a..8743066cff04 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 @@ -17,12 +17,9 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import google.api_core -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - operations_v1, - retry as retries, -) +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_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.cloud.vision_v1 import gapic_version as package_version 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 58212cf89dc9..201a6cdaf954 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 @@ -20,13 +20,9 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - grpc_helpers_async, - operations_v1, - retry_async as retries, -) +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.auth.transport.grpc import SslCredentials # type: ignore from google.cloud.vision_v1.types import product_search_service 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 426da4762a11..33a87601566d 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 @@ -19,14 +19,9 @@ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - operations_v1, - rest_helpers, - rest_streaming, - retry as retries, -) +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_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.cloud.vision_v1.types import product_search_service 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 a5a9a80e648a..51878b7d7785 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,12 +17,8 @@ from typing import MutableMapping, MutableSequence -from google.cloud.vision_v1.types import ( - geometry, - product_search, - text_annotation, - web_detection as gcv_web_detection, -) +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 from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore from google.type import ( 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 799a51cba00f..2474d088ba49 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 @@ -29,11 +29,9 @@ Union, ) -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - retry_async as retries, -) +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.cloud.vision_v1p1beta1 import gapic_version as package_version 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 f5883928fa1f..57ff52d008e4 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 @@ -34,12 +34,10 @@ ) import warnings -from google.api_core import ( - client_options as client_options_lib, - exceptions as core_exceptions, - gapic_v1, - retry as retries, -) +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 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 2b2198963dfc..76bc32f896c7 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 @@ -17,7 +17,9 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import google.api_core -from google.api_core import exceptions as core_exceptions, gapic_v1, retry as retries +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.cloud.vision_v1p1beta1 import gapic_version as package_version 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 67ed5de0b2b6..956faa1dcf75 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 @@ -20,12 +20,9 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - grpc_helpers_async, - retry_async as retries, -) +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.cloud.vision_v1p1beta1.types import image_annotator 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 952a63d2adb1..cc95afaff446 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 @@ -19,13 +19,9 @@ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - rest_helpers, - rest_streaming, - retry as retries, -) +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.cloud.vision_v1p1beta1.types import image_annotator 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 48b5103bbfd8..d649ef8abd38 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,11 +17,8 @@ from typing import MutableMapping, MutableSequence -from google.cloud.vision_v1p1beta1.types import ( - geometry, - text_annotation, - web_detection as gcv_web_detection, -) +from google.cloud.vision_v1p1beta1.types import geometry, 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 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 8d6093e08ead..0528a39427ab 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 @@ -30,11 +30,9 @@ ) import uuid -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - retry_async as retries, -) +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.cloud.vision_v1p2beta1 import gapic_version as package_version 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 b1688e702763..1021ff959735 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 @@ -35,12 +35,10 @@ import uuid import warnings -from google.api_core import ( - client_options as client_options_lib, - exceptions as core_exceptions, - gapic_v1, - retry as retries, -) +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 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 1bc69a9b1fd2..6b9732e8deb5 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 @@ -17,12 +17,9 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import google.api_core -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - operations_v1, - retry as retries, -) +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_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.cloud.vision_v1p2beta1 import gapic_version as package_version 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 965edb9418fa..ccd791fc5b4f 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 @@ -20,13 +20,9 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - grpc_helpers_async, - operations_v1, - retry_async as retries, -) +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.auth.transport.grpc import SslCredentials # type: ignore from google.cloud.vision_v1p2beta1.types import image_annotator 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 35ce5fc63dc5..74c75fb0bb2e 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 @@ -19,14 +19,9 @@ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - operations_v1, - rest_helpers, - rest_streaming, - retry as retries, -) +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_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.cloud.vision_v1p2beta1.types import image_annotator 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 62deae4d4b00..936810b1b923 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,11 +17,8 @@ from typing import MutableMapping, MutableSequence -from google.cloud.vision_v1p2beta1.types import ( - geometry, - text_annotation, - web_detection as gcv_web_detection, -) +from google.cloud.vision_v1p2beta1.types import geometry, 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 ( 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 15bf7d52ab42..255facc5fd8b 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 @@ -29,11 +29,9 @@ Union, ) -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - retry_async as retries, -) +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.cloud.vision_v1p3beta1 import gapic_version as package_version 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 462acb262d44..31cbc1f0e797 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 @@ -34,12 +34,10 @@ ) import warnings -from google.api_core import ( - client_options as client_options_lib, - exceptions as core_exceptions, - gapic_v1, - retry as retries, -) +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 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 128bd120a285..ebff7014f168 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 @@ -17,12 +17,9 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import google.api_core -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - operations_v1, - retry as retries, -) +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_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.cloud.vision_v1p3beta1 import gapic_version as package_version 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 ba1f798e163c..3cb7dcffbc4a 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 @@ -20,13 +20,9 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - grpc_helpers_async, - operations_v1, - retry_async as retries, -) +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.auth.transport.grpc import SslCredentials # type: ignore from google.cloud.vision_v1p3beta1.types import image_annotator 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 0a427962974a..eedfe15adcf2 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 @@ -19,14 +19,9 @@ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - operations_v1, - rest_helpers, - rest_streaming, - retry as retries, -) +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_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.cloud.vision_v1p3beta1.types import image_annotator 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 5fbf7d714bbd..42d5029dd52c 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 @@ -29,11 +29,9 @@ Union, ) -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - retry_async as retries, -) +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.cloud.vision_v1p3beta1 import gapic_version as package_version 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 64f764ce0616..71b1f3d4ebd0 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 @@ -34,12 +34,10 @@ ) import warnings -from google.api_core import ( - client_options as client_options_lib, - exceptions as core_exceptions, - gapic_v1, - retry as retries, -) +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 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 ead863e7b042..9913867a51ff 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 @@ -25,7 +25,9 @@ Union, ) -from google.api_core import gapic_v1, retry as retries, retry_async as retries_async +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] 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 cd86b3fd2fc4..44a5727133f6 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 @@ -17,12 +17,9 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import google.api_core -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - operations_v1, - retry as retries, -) +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_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.cloud.vision_v1p3beta1 import gapic_version as package_version 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 bda008538473..e10aa44e93e3 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 @@ -20,13 +20,9 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - grpc_helpers_async, - operations_v1, - retry_async as retries, -) +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.auth.transport.grpc import SslCredentials # type: ignore from google.cloud.vision_v1p3beta1.types import product_search_service 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 21ae4406ad0f..4da64b85fb72 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 @@ -19,14 +19,9 @@ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - operations_v1, - rest_helpers, - rest_streaming, - retry as retries, -) +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_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.cloud.vision_v1p3beta1.types import product_search_service 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 7d48a396f249..a6a62c409175 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 @@ -21,8 +21,8 @@ geometry, product_search, text_annotation, - web_detection as gcv_web_detection, ) +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 ( 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 83dfce6f05fb..c621954c3af7 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 @@ -29,11 +29,9 @@ Union, ) -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - retry_async as retries, -) +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.cloud.vision_v1p4beta1 import gapic_version as package_version 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 da561c0aa36a..0fbe93b97a20 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 @@ -34,12 +34,10 @@ ) import warnings -from google.api_core import ( - client_options as client_options_lib, - exceptions as core_exceptions, - gapic_v1, - retry as retries, -) +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 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 736dc63f6157..7dc31f163a50 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 @@ -17,12 +17,9 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import google.api_core -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - operations_v1, - retry as retries, -) +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_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.cloud.vision_v1p4beta1 import gapic_version as package_version 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 76566ceb1b60..a1c672565bf8 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 @@ -20,13 +20,9 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - grpc_helpers_async, - operations_v1, - retry_async as retries, -) +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.auth.transport.grpc import SslCredentials # type: ignore from google.cloud.vision_v1p4beta1.types import image_annotator 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 1b11f25fac41..8274aa60cb75 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 @@ -19,14 +19,9 @@ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - operations_v1, - rest_helpers, - rest_streaming, - retry as retries, -) +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_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.cloud.vision_v1p4beta1.types import image_annotator 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 37f64945dba0..aaeb8a588a67 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 @@ -29,11 +29,9 @@ Union, ) -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - retry_async as retries, -) +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.cloud.vision_v1p4beta1 import gapic_version as package_version 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 52d42bca02f3..60d066a17fc1 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 @@ -34,12 +34,10 @@ ) import warnings -from google.api_core import ( - client_options as client_options_lib, - exceptions as core_exceptions, - gapic_v1, - retry as retries, -) +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 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 3748d92defa5..d6d1065fd30d 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 @@ -25,7 +25,9 @@ Union, ) -from google.api_core import gapic_v1, retry as retries, retry_async as retries_async +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] 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 8127e41f9141..b697cd62f256 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 @@ -17,12 +17,9 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import google.api_core -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - operations_v1, - retry as retries, -) +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_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.cloud.vision_v1p4beta1 import gapic_version as package_version 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 42715e1e4c19..b7382ad9644c 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 @@ -20,13 +20,9 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - grpc_helpers_async, - operations_v1, - retry_async as retries, -) +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.auth.transport.grpc import SslCredentials # type: ignore from google.cloud.vision_v1p4beta1.types import product_search_service 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 c203412eb20a..3da338ce5069 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 @@ -19,14 +19,9 @@ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - exceptions as core_exceptions, - gapic_v1, - operations_v1, - rest_helpers, - rest_streaming, - retry as retries, -) +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_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.cloud.vision_v1p4beta1.types import product_search_service 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 73f89b3fe35e..99da67beca01 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 @@ -22,8 +22,8 @@ geometry, product_search, text_annotation, - web_detection as gcv_web_detection, ) +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 ( 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 e4b54134cdfa..e8924ad9c02b 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 @@ -45,7 +45,6 @@ from google.api_core import ( client_options, - exceptions as core_exceptions, future, gapic_v1, grpc_helpers, @@ -54,8 +53,9 @@ operation_async, # type: ignore operations_v1, path_template, - retry as retries, ) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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 090890c91213..54e3f35b36fc 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 @@ -45,7 +45,6 @@ from google.api_core import ( client_options, - exceptions as core_exceptions, future, gapic_v1, grpc_helpers, @@ -54,8 +53,9 @@ operation_async, # type: ignore operations_v1, path_template, - retry as retries, ) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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 19ca8958e6c7..6ea4fa37bb1a 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 @@ -45,13 +45,13 @@ from google.api_core import ( client_options, - exceptions as core_exceptions, gapic_v1, grpc_helpers, grpc_helpers_async, path_template, - retry as retries, ) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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 2f36e9882594..fa034915efd9 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 @@ -46,7 +46,6 @@ from google.api_core import ( client_options, - exceptions as core_exceptions, future, gapic_v1, grpc_helpers, @@ -55,8 +54,9 @@ operation_async, # type: ignore operations_v1, path_template, - retry as retries, ) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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 d65744bbd313..d32da9ee1d1a 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 @@ -45,7 +45,6 @@ from google.api_core import ( client_options, - exceptions as core_exceptions, future, gapic_v1, grpc_helpers, @@ -54,8 +53,9 @@ operation_async, # type: ignore operations_v1, path_template, - retry as retries, ) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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 14b15fb0178e..bc315c675b62 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 @@ -45,7 +45,6 @@ from google.api_core import ( client_options, - exceptions as core_exceptions, future, gapic_v1, grpc_helpers, @@ -54,8 +53,9 @@ operation_async, # type: ignore operations_v1, path_template, - retry as retries, ) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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 7f463ae50442..2a2decdb61e2 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 @@ -45,7 +45,6 @@ from google.api_core import ( client_options, - exceptions as core_exceptions, future, gapic_v1, grpc_helpers, @@ -54,8 +53,9 @@ operation_async, # type: ignore operations_v1, path_template, - retry as retries, ) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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 9b16a039d1d6..5ea40569d236 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 @@ -45,7 +45,6 @@ from google.api_core import ( client_options, - exceptions as core_exceptions, future, gapic_v1, grpc_helpers, @@ -54,8 +53,9 @@ operation_async, # type: ignore operations_v1, path_template, - retry as retries, ) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError