From ff4d87afed5ca566d896337fe88b61165e30ddf7 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Mon, 4 Aug 2025 12:57:24 +0000 Subject: [PATCH 1/2] feat: add inventories API client libraries for v1 PiperOrigin-RevId: 790685328 Source-Link: https://github.com/googleapis/googleapis/commit/bf4323361090d10caee451c97f157a21b9403d61 Source-Link: https://github.com/googleapis/googleapis-gen/commit/ca3ae42e3d7169e537d3aaa6dfbc461cf36264a3 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLXNob3BwaW5nLW1lcmNoYW50LWludmVudG9yaWVzLy5Pd2xCb3QueWFtbCIsImgiOiJjYTNhZTQyZTNkNzE2OWU1MzdkM2FhYTZkZmJjNDYxY2YzNjI2NGEzIn0= --- .../v1/.coveragerc | 13 + .../v1/.flake8 | 34 + .../v1/LICENSE | 202 + .../v1/MANIFEST.in | 20 + .../v1/README.rst | 143 + .../v1/docs/_static/custom.css | 20 + .../v1/docs/_templates/layout.html | 50 + .../v1/docs/conf.py | 385 ++ .../v1/docs/index.rst | 10 + .../local_inventory_service.rst | 10 + .../regional_inventory_service.rst | 10 + .../merchant_inventories_v1/services_.rst | 7 + .../docs/merchant_inventories_v1/types_.rst | 6 + .../v1/docs/multiprocessing.rst | 7 + .../shopping/merchant_inventories/__init__.py | 55 + .../merchant_inventories/gapic_version.py | 16 + .../shopping/merchant_inventories/py.typed | 2 + .../merchant_inventories_v1/__init__.py | 56 + .../gapic_metadata.json | 137 + .../merchant_inventories_v1/gapic_version.py | 16 + .../shopping/merchant_inventories_v1/py.typed | 2 + .../services/__init__.py | 15 + .../local_inventory_service/__init__.py | 22 + .../local_inventory_service/async_client.py | 590 +++ .../local_inventory_service/client.py | 949 +++++ .../local_inventory_service/pagers.py | 166 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 188 + .../transports/grpc.py | 418 ++ .../transports/grpc_asyncio.py | 449 ++ .../transports/rest.py | 640 +++ .../transports/rest_base.py | 213 + .../regional_inventory_service/__init__.py | 22 + .../async_client.py | 596 +++ .../regional_inventory_service/client.py | 955 +++++ .../regional_inventory_service/pagers.py | 166 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 188 + .../transports/grpc.py | 419 ++ .../transports/grpc_asyncio.py | 450 ++ .../transports/rest.py | 644 +++ .../transports/rest_base.py | 213 + .../merchant_inventories_v1/types/__init__.py | 48 + .../types/inventories_common.py | 281 ++ .../types/localinventory.py | 196 + .../types/regionalinventory.py | 197 + .../v1/mypy.ini | 3 + .../v1/noxfile.py | 591 +++ ...ry_service_delete_local_inventory_async.py | 50 + ...ory_service_delete_local_inventory_sync.py | 50 + ...ry_service_insert_local_inventory_async.py | 56 + ...ory_service_insert_local_inventory_sync.py | 56 + ...ry_service_list_local_inventories_async.py | 53 + ...ory_service_list_local_inventories_sync.py | 53 + ...service_delete_regional_inventory_async.py | 50 + ..._service_delete_regional_inventory_sync.py | 50 + ...service_insert_regional_inventory_async.py | 56 + ..._service_insert_regional_inventory_sync.py | 56 + ...service_list_regional_inventories_async.py | 53 + ..._service_list_regional_inventories_sync.py | 53 + ...ogle.shopping.merchant.inventories.v1.json | 953 +++++ .../fixup_merchant_inventories_v1_keywords.py | 181 + .../v1/setup.py | 99 + .../v1/testing/constraints-3.10.txt | 7 + .../v1/testing/constraints-3.11.txt | 7 + .../v1/testing/constraints-3.12.txt | 7 + .../v1/testing/constraints-3.13.txt | 12 + .../v1/testing/constraints-3.7.txt | 11 + .../v1/testing/constraints-3.8.txt | 7 + .../v1/testing/constraints-3.9.txt | 7 + .../v1/tests/__init__.py | 16 + .../v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../gapic/merchant_inventories_v1/__init__.py | 16 + .../test_local_inventory_service.py | 3632 ++++++++++++++++ .../test_regional_inventory_service.py | 3632 ++++++++++++++++ .../v1beta/.coveragerc | 13 + .../v1beta/.flake8 | 34 + .../v1beta/LICENSE | 202 + .../v1beta/MANIFEST.in | 20 + .../v1beta/README.rst | 143 + .../v1beta/docs/_static/custom.css | 20 + .../v1beta/docs/_templates/layout.html | 50 + .../v1beta/docs/conf.py | 385 ++ .../v1beta/docs/index.rst | 10 + .../local_inventory_service.rst | 10 + .../regional_inventory_service.rst | 10 + .../merchant_inventories_v1beta/services_.rst | 7 + .../merchant_inventories_v1beta/types_.rst | 6 + .../v1beta/docs/multiprocessing.rst | 7 + .../shopping/merchant_inventories/__init__.py | 51 + .../merchant_inventories/gapic_version.py | 16 + .../shopping/merchant_inventories/py.typed | 2 + .../merchant_inventories_v1beta/__init__.py | 52 + .../gapic_metadata.json | 137 + .../gapic_version.py | 16 + .../merchant_inventories_v1beta/py.typed | 2 + .../services/__init__.py | 15 + .../local_inventory_service/__init__.py | 22 + .../local_inventory_service/async_client.py | 591 +++ .../local_inventory_service/client.py | 950 +++++ .../local_inventory_service/pagers.py | 166 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 188 + .../transports/grpc.py | 418 ++ .../transports/grpc_asyncio.py | 449 ++ .../transports/rest.py | 640 +++ .../transports/rest_base.py | 213 + .../regional_inventory_service/__init__.py | 22 + .../async_client.py | 597 +++ .../regional_inventory_service/client.py | 956 +++++ .../regional_inventory_service/pagers.py | 166 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 188 + .../transports/grpc.py | 419 ++ .../transports/grpc_asyncio.py | 450 ++ .../transports/rest.py | 644 +++ .../transports/rest_base.py | 213 + .../types/__init__.py | 42 + .../types/localinventory.py | 281 ++ .../types/regionalinventory.py | 236 ++ .../v1beta/mypy.ini | 3 + .../v1beta/noxfile.py | 591 +++ ...ry_service_delete_local_inventory_async.py | 50 + ...ory_service_delete_local_inventory_sync.py | 50 + ...ry_service_insert_local_inventory_async.py | 56 + ...ory_service_insert_local_inventory_sync.py | 56 + ...ry_service_list_local_inventories_async.py | 53 + ...ory_service_list_local_inventories_sync.py | 53 + ...service_delete_regional_inventory_async.py | 50 + ..._service_delete_regional_inventory_sync.py | 50 + ...service_insert_regional_inventory_async.py | 56 + ..._service_insert_regional_inventory_sync.py | 56 + ...service_list_regional_inventories_async.py | 53 + ..._service_list_regional_inventories_sync.py | 53 + ....shopping.merchant.inventories.v1beta.json | 953 +++++ ...up_merchant_inventories_v1beta_keywords.py | 181 + .../v1beta/setup.py | 99 + .../v1beta/testing/constraints-3.10.txt | 7 + .../v1beta/testing/constraints-3.11.txt | 7 + .../v1beta/testing/constraints-3.12.txt | 7 + .../v1beta/testing/constraints-3.13.txt | 12 + .../v1beta/testing/constraints-3.7.txt | 11 + .../v1beta/testing/constraints-3.8.txt | 7 + .../v1beta/testing/constraints-3.9.txt | 7 + .../v1beta/tests/__init__.py | 16 + .../v1beta/tests/unit/__init__.py | 16 + .../v1beta/tests/unit/gapic/__init__.py | 16 + .../merchant_inventories_v1beta/__init__.py | 16 + .../test_local_inventory_service.py | 3666 +++++++++++++++++ .../test_regional_inventory_service.py | 3638 ++++++++++++++++ 155 files changed, 38211 insertions(+) create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/.coveragerc create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/.flake8 create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/LICENSE create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/MANIFEST.in create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/docs/_templates/layout.html create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/docs/conf.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/docs/index.rst create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/docs/merchant_inventories_v1/local_inventory_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/docs/merchant_inventories_v1/regional_inventory_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/docs/merchant_inventories_v1/services_.rst create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/docs/merchant_inventories_v1/types_.rst create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/docs/multiprocessing.rst create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories/gapic_version.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories/py.typed create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/gapic_version.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/py.typed create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/inventories_common.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/localinventory.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/regionalinventory.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/mypy.ini create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/noxfile.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_delete_local_inventory_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_delete_local_inventory_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_insert_local_inventory_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_insert_local_inventory_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_list_local_inventories_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_list_local_inventories_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_delete_regional_inventory_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_delete_regional_inventory_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_insert_regional_inventory_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_insert_regional_inventory_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_list_regional_inventories_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_list_regional_inventories_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1.json create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/scripts/fixup_merchant_inventories_v1_keywords.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/setup.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/tests/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/merchant_inventories_v1/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/merchant_inventories_v1/test_local_inventory_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/merchant_inventories_v1/test_regional_inventory_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/.coveragerc create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/.flake8 create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/LICENSE create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/MANIFEST.in create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/_static/custom.css create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/_templates/layout.html create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/conf.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/index.rst create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/local_inventory_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/regional_inventory_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/services_.rst create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/types_.rst create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/multiprocessing.rst create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/gapic_version.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/py.typed create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_metadata.json create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_version.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/py.typed create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/localinventory.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/regionalinventory.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/mypy.ini create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/noxfile.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1beta.json create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/scripts/fixup_merchant_inventories_v1beta_keywords.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/setup.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_local_inventory_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_regional_inventory_service.py diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/.coveragerc b/owl-bot-staging/google-shopping-merchant-inventories/v1/.coveragerc new file mode 100644 index 000000000000..b3835b541d48 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/shopping/merchant_inventories/__init__.py + google/shopping/merchant_inventories/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/.flake8 b/owl-bot-staging/google-shopping-merchant-inventories/v1/.flake8 new file mode 100644 index 000000000000..90316de21489 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/.flake8 @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +[flake8] +# TODO(https://github.com/googleapis/gapic-generator-python/issues/2333): +# Resolve flake8 lint issues +ignore = E203, E231, E266, E501, W503 +exclude = + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2333): + # Ensure that generated code passes flake8 lint + **/gapic/** + **/services/** + **/types/** + # Exclude Protobuf gencode + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/LICENSE b/owl-bot-staging/google-shopping-merchant-inventories/v1/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/MANIFEST.in b/owl-bot-staging/google-shopping-merchant-inventories/v1/MANIFEST.in new file mode 100644 index 000000000000..dae249ec8976 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/MANIFEST.in @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +include README.rst LICENSE +recursive-include google *.py *.pyi *.json *.proto py.typed +recursive-include tests * +global-exclude *.py[co] +global-exclude __pycache__ diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/README.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1/README.rst new file mode 100644 index 000000000000..373e5600ce98 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/README.rst @@ -0,0 +1,143 @@ +Python Client for Google Shopping Merchant Inventories API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Shopping Merchant Inventories API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library + + +Logging +------- + +This library uses the standard Python :code:`logging` functionality to log some RPC events that could be of interest for debugging and monitoring purposes. +Note the following: + +#. Logs may contain sensitive information. Take care to **restrict access to the logs** if they are saved, whether it be on local storage or on Google Cloud Logging. +#. Google may refine the occurrence, level, and content of various log messages in this library without flagging such changes as breaking. **Do not depend on immutability of the logging events**. +#. By default, the logging events from this library are not handled. You must **explicitly configure log handling** using one of the mechanisms below. + + +Simple, environment-based configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To enable logging for this library without any changes in your code, set the :code:`GOOGLE_SDK_PYTHON_LOGGING_SCOPE` environment variable to a valid Google +logging scope. This configures handling of logging events (at level :code:`logging.DEBUG` or higher) from this library in a default manner, emitting the logged +messages in a structured format. It does not currently allow customizing the logging levels captured nor the handlers, formatters, etc. used for any logging +event. + +A logging scope is a period-separated namespace that begins with :code:`google`, identifying the Python module or package to log. + +- Valid logging scopes: :code:`google`, :code:`google.cloud.asset.v1`, :code:`google.api`, :code:`google.auth`, etc. +- Invalid logging scopes: :code:`foo`, :code:`123`, etc. + +**NOTE**: If the logging scope is invalid, the library does not set up any logging handlers. + + +Examples +^^^^^^^^ + +- Enabling the default handler for all Google-based loggers + +.. code-block:: console + + export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google + +- Enabling the default handler for a specific Google module (for a client library called :code:`library_v1`): + +.. code-block:: console + + export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google.cloud.library_v1 + + +Advanced, code-based configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can also configure a valid logging scope using Python's standard `logging` mechanism. + + +Examples +^^^^^^^^ + +- Configuring a handler for all Google-based loggers + +.. code-block:: python + + import logging + + from google.cloud.translate_v3 import translate + + base_logger = logging.getLogger("google") + base_logger.addHandler(logging.StreamHandler()) + base_logger.setLevel(logging.DEBUG) + +- Configuring a handler for a specific Google module (for a client library called :code:`library_v1`): + +.. code-block:: python + + import logging + + from google.cloud.translate_v3 import translate + + base_logger = logging.getLogger("google.cloud.library_v1") + base_logger.addHandler(logging.StreamHandler()) + base_logger.setLevel(logging.DEBUG) + + +Logging details +~~~~~~~~~~~~~~~ + +#. Regardless of which of the mechanisms above you use to configure logging for this library, by default logging events are not propagated up to the root + logger from the `google`-level logger. If you need the events to be propagated to the root logger, you must explicitly set + :code:`logging.getLogger("google").propagate = True` in your code. +#. You can mix the different logging configurations above for different Google modules. For example, you may want use a code-based logging configuration for + one library, but decide you need to also set up environment-based logging configuration for another library. + + #. If you attempt to use both code-based and environment-based configuration for the same module, the environment-based configuration will be ineffectual + if the code -based configuration gets applied first. + +#. The Google-specific logging configurations (default handlers for environment-based configuration; not propagating logging events to the root logger) get + executed the first time *any* client library is instantiated in your application, and only if the affected loggers have not been previously configured. + (This is the reason for 2.i. above.) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/_static/custom.css b/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/_static/custom.css new file mode 100644 index 000000000000..b0a295464b23 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/_static/custom.css @@ -0,0 +1,20 @@ +div#python2-eol { + border-color: red; + border-width: medium; +} + +/* Ensure minimum width for 'Parameters' / 'Returns' column */ +dl.field-list > dt { + min-width: 100px +} + +/* Insert space between methods for readability */ +dl.method { + padding-top: 10px; + padding-bottom: 10px +} + +/* Insert empty space between classes */ +dl.class { + padding-bottom: 50px +} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/_templates/layout.html b/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/_templates/layout.html new file mode 100644 index 000000000000..95e9c77fcfe1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/_templates/layout.html @@ -0,0 +1,50 @@ + +{% extends "!layout.html" %} +{%- block content %} +{%- if theme_fixed_sidebar|lower == 'true' %} +
+ {{ sidebar() }} + {%- block document %} +
+ {%- if render_sidebar %} +
+ {%- endif %} + + {%- block relbar_top %} + {%- if theme_show_relbar_top|tobool %} + + {%- endif %} + {% endblock %} + +
+
+ As of January 1, 2020 this library no longer supports Python 2 on the latest released version. + Library versions released prior to that date will continue to be available. For more information please + visit Python 2 support on Google Cloud. +
+ {% block body %} {% endblock %} +
+ + {%- block relbar_bottom %} + {%- if theme_show_relbar_bottom|tobool %} + + {%- endif %} + {% endblock %} + + {%- if render_sidebar %} +
+ {%- endif %} +
+ {%- endblock %} +
+
+{%- else %} +{{ super() }} +{%- endif %} +{%- endblock %} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/conf.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/conf.py new file mode 100644 index 000000000000..b4a1101f35ed --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/conf.py @@ -0,0 +1,385 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-shopping-merchant-inventories documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# 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 +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +# For plugins that can not read conf.py. +# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 +sys.path.insert(0, os.path.abspath(".")) + +__version__ = "" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.5.0" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.doctest", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", + "recommonmark", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_options = {"members": True} +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# source_suffix = ['.rst', '.md'] +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-shopping-merchant-inventories" +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 +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = [ + "_build", + "**/.nox/**/*", + "samples/AUTHORING_GUIDE.md", + "samples/CONTRIBUTING.md", + "samples/snippets/README.rst", +] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Shopping Client Libraries for google-shopping-merchant-inventories", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-shopping-merchant-inventories-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-shopping-merchant-inventories.tex", + u"google-shopping-merchant-inventories Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-shopping-merchant-inventories", + "google-shopping-merchant-inventories Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-shopping-merchant-inventories", + "google-shopping-merchant-inventories Documentation", + author, + "google-shopping-merchant-inventories", + "google-shopping-merchant-inventories Library", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("https://python.readthedocs.org/en/latest/", None), + "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None), + "google.api_core": ( + "https://googleapis.dev/python/google-api-core/latest/", + None, + ), + "grpc": ("https://grpc.github.io/grpc/python/", None), + "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/index.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/index.rst new file mode 100644 index 000000000000..f63408727d88 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/index.rst @@ -0,0 +1,10 @@ +.. include:: multiprocessing.rst + + +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + merchant_inventories_v1/services_ + merchant_inventories_v1/types_ diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/merchant_inventories_v1/local_inventory_service.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/merchant_inventories_v1/local_inventory_service.rst new file mode 100644 index 000000000000..e576e510ea83 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/merchant_inventories_v1/local_inventory_service.rst @@ -0,0 +1,10 @@ +LocalInventoryService +--------------------------------------- + +.. automodule:: google.shopping.merchant_inventories_v1.services.local_inventory_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_inventories_v1.services.local_inventory_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/merchant_inventories_v1/regional_inventory_service.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/merchant_inventories_v1/regional_inventory_service.rst new file mode 100644 index 000000000000..41d4251adbae --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/merchant_inventories_v1/regional_inventory_service.rst @@ -0,0 +1,10 @@ +RegionalInventoryService +------------------------------------------ + +.. automodule:: google.shopping.merchant_inventories_v1.services.regional_inventory_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_inventories_v1.services.regional_inventory_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/merchant_inventories_v1/services_.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/merchant_inventories_v1/services_.rst new file mode 100644 index 000000000000..d612dbb9aab6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/merchant_inventories_v1/services_.rst @@ -0,0 +1,7 @@ +Services for Google Shopping Merchant Inventories v1 API +======================================================== +.. toctree:: + :maxdepth: 2 + + local_inventory_service + regional_inventory_service diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/merchant_inventories_v1/types_.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/merchant_inventories_v1/types_.rst new file mode 100644 index 000000000000..784c040a6c29 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/merchant_inventories_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Shopping Merchant Inventories v1 API +===================================================== + +.. automodule:: google.shopping.merchant_inventories_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/multiprocessing.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/multiprocessing.rst new file mode 100644 index 000000000000..536d17b2ea65 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/multiprocessing.rst @@ -0,0 +1,7 @@ +.. note:: + + Because this client uses :mod:`grpc` library, it is safe to + share instances across threads. In multiprocessing scenarios, the best + practice is to create client instances *after* the invocation of + :func:`os.fork` by :class:`multiprocessing.pool.Pool` or + :class:`multiprocessing.Process`. diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories/__init__.py new file mode 100644 index 000000000000..a859205efe72 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories/__init__.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.shopping.merchant_inventories import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.shopping.merchant_inventories_v1.services.local_inventory_service.client import LocalInventoryServiceClient +from google.shopping.merchant_inventories_v1.services.local_inventory_service.async_client import LocalInventoryServiceAsyncClient +from google.shopping.merchant_inventories_v1.services.regional_inventory_service.client import RegionalInventoryServiceClient +from google.shopping.merchant_inventories_v1.services.regional_inventory_service.async_client import RegionalInventoryServiceAsyncClient + +from google.shopping.merchant_inventories_v1.types.inventories_common import LocalInventoryAttributes +from google.shopping.merchant_inventories_v1.types.inventories_common import RegionalInventoryAttributes +from google.shopping.merchant_inventories_v1.types.localinventory import DeleteLocalInventoryRequest +from google.shopping.merchant_inventories_v1.types.localinventory import InsertLocalInventoryRequest +from google.shopping.merchant_inventories_v1.types.localinventory import ListLocalInventoriesRequest +from google.shopping.merchant_inventories_v1.types.localinventory import ListLocalInventoriesResponse +from google.shopping.merchant_inventories_v1.types.localinventory import LocalInventory +from google.shopping.merchant_inventories_v1.types.regionalinventory import DeleteRegionalInventoryRequest +from google.shopping.merchant_inventories_v1.types.regionalinventory import InsertRegionalInventoryRequest +from google.shopping.merchant_inventories_v1.types.regionalinventory import ListRegionalInventoriesRequest +from google.shopping.merchant_inventories_v1.types.regionalinventory import ListRegionalInventoriesResponse +from google.shopping.merchant_inventories_v1.types.regionalinventory import RegionalInventory + +__all__ = ('LocalInventoryServiceClient', + 'LocalInventoryServiceAsyncClient', + 'RegionalInventoryServiceClient', + 'RegionalInventoryServiceAsyncClient', + 'LocalInventoryAttributes', + 'RegionalInventoryAttributes', + 'DeleteLocalInventoryRequest', + 'InsertLocalInventoryRequest', + 'ListLocalInventoriesRequest', + 'ListLocalInventoriesResponse', + 'LocalInventory', + 'DeleteRegionalInventoryRequest', + 'InsertRegionalInventoryRequest', + 'ListRegionalInventoriesRequest', + 'ListRegionalInventoriesResponse', + 'RegionalInventory', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories/gapic_version.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories/gapic_version.py new file mode 100644 index 000000000000..20a9cd975b02 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories/py.typed b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories/py.typed new file mode 100644 index 000000000000..993f00a7e3c3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-shopping-merchant-inventories package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/__init__.py new file mode 100644 index 000000000000..501eb2a58870 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/__init__.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.shopping.merchant_inventories_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.local_inventory_service import LocalInventoryServiceClient +from .services.local_inventory_service import LocalInventoryServiceAsyncClient +from .services.regional_inventory_service import RegionalInventoryServiceClient +from .services.regional_inventory_service import RegionalInventoryServiceAsyncClient + +from .types.inventories_common import LocalInventoryAttributes +from .types.inventories_common import RegionalInventoryAttributes +from .types.localinventory import DeleteLocalInventoryRequest +from .types.localinventory import InsertLocalInventoryRequest +from .types.localinventory import ListLocalInventoriesRequest +from .types.localinventory import ListLocalInventoriesResponse +from .types.localinventory import LocalInventory +from .types.regionalinventory import DeleteRegionalInventoryRequest +from .types.regionalinventory import InsertRegionalInventoryRequest +from .types.regionalinventory import ListRegionalInventoriesRequest +from .types.regionalinventory import ListRegionalInventoriesResponse +from .types.regionalinventory import RegionalInventory + +__all__ = ( + 'LocalInventoryServiceAsyncClient', + 'RegionalInventoryServiceAsyncClient', +'DeleteLocalInventoryRequest', +'DeleteRegionalInventoryRequest', +'InsertLocalInventoryRequest', +'InsertRegionalInventoryRequest', +'ListLocalInventoriesRequest', +'ListLocalInventoriesResponse', +'ListRegionalInventoriesRequest', +'ListRegionalInventoriesResponse', +'LocalInventory', +'LocalInventoryAttributes', +'LocalInventoryServiceClient', +'RegionalInventory', +'RegionalInventoryAttributes', +'RegionalInventoryServiceClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/gapic_metadata.json b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/gapic_metadata.json new file mode 100644 index 000000000000..aaff04bf78c4 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/gapic_metadata.json @@ -0,0 +1,137 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.shopping.merchant_inventories_v1", + "protoPackage": "google.shopping.merchant.inventories.v1", + "schema": "1.0", + "services": { + "LocalInventoryService": { + "clients": { + "grpc": { + "libraryClient": "LocalInventoryServiceClient", + "rpcs": { + "DeleteLocalInventory": { + "methods": [ + "delete_local_inventory" + ] + }, + "InsertLocalInventory": { + "methods": [ + "insert_local_inventory" + ] + }, + "ListLocalInventories": { + "methods": [ + "list_local_inventories" + ] + } + } + }, + "grpc-async": { + "libraryClient": "LocalInventoryServiceAsyncClient", + "rpcs": { + "DeleteLocalInventory": { + "methods": [ + "delete_local_inventory" + ] + }, + "InsertLocalInventory": { + "methods": [ + "insert_local_inventory" + ] + }, + "ListLocalInventories": { + "methods": [ + "list_local_inventories" + ] + } + } + }, + "rest": { + "libraryClient": "LocalInventoryServiceClient", + "rpcs": { + "DeleteLocalInventory": { + "methods": [ + "delete_local_inventory" + ] + }, + "InsertLocalInventory": { + "methods": [ + "insert_local_inventory" + ] + }, + "ListLocalInventories": { + "methods": [ + "list_local_inventories" + ] + } + } + } + } + }, + "RegionalInventoryService": { + "clients": { + "grpc": { + "libraryClient": "RegionalInventoryServiceClient", + "rpcs": { + "DeleteRegionalInventory": { + "methods": [ + "delete_regional_inventory" + ] + }, + "InsertRegionalInventory": { + "methods": [ + "insert_regional_inventory" + ] + }, + "ListRegionalInventories": { + "methods": [ + "list_regional_inventories" + ] + } + } + }, + "grpc-async": { + "libraryClient": "RegionalInventoryServiceAsyncClient", + "rpcs": { + "DeleteRegionalInventory": { + "methods": [ + "delete_regional_inventory" + ] + }, + "InsertRegionalInventory": { + "methods": [ + "insert_regional_inventory" + ] + }, + "ListRegionalInventories": { + "methods": [ + "list_regional_inventories" + ] + } + } + }, + "rest": { + "libraryClient": "RegionalInventoryServiceClient", + "rpcs": { + "DeleteRegionalInventory": { + "methods": [ + "delete_regional_inventory" + ] + }, + "InsertRegionalInventory": { + "methods": [ + "insert_regional_inventory" + ] + }, + "ListRegionalInventories": { + "methods": [ + "list_regional_inventories" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/gapic_version.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/gapic_version.py new file mode 100644 index 000000000000..20a9cd975b02 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/py.typed b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/py.typed new file mode 100644 index 000000000000..993f00a7e3c3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-shopping-merchant-inventories package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/__init__.py new file mode 100644 index 000000000000..cbf94b283c70 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/__init__.py new file mode 100644 index 000000000000..4b805a80aace --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import LocalInventoryServiceClient +from .async_client import LocalInventoryServiceAsyncClient + +__all__ = ( + 'LocalInventoryServiceClient', + 'LocalInventoryServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/async_client.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/async_client.py new file mode 100644 index 000000000000..11fb9a200efe --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/async_client.py @@ -0,0 +1,590 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import 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.shopping.merchant_inventories_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.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + + +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.shopping.merchant_inventories_v1.services.local_inventory_service import pagers +from google.shopping.merchant_inventories_v1.types import inventories_common +from google.shopping.merchant_inventories_v1.types import localinventory +from .transports.base import LocalInventoryServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import LocalInventoryServiceGrpcAsyncIOTransport +from .client import LocalInventoryServiceClient + +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 LocalInventoryServiceAsyncClient: + """Service to manage local inventory for products""" + + _client: LocalInventoryServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = LocalInventoryServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = LocalInventoryServiceClient._DEFAULT_UNIVERSE + + local_inventory_path = staticmethod(LocalInventoryServiceClient.local_inventory_path) + parse_local_inventory_path = staticmethod(LocalInventoryServiceClient.parse_local_inventory_path) + common_billing_account_path = staticmethod(LocalInventoryServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(LocalInventoryServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(LocalInventoryServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(LocalInventoryServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(LocalInventoryServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(LocalInventoryServiceClient.parse_common_organization_path) + common_project_path = staticmethod(LocalInventoryServiceClient.common_project_path) + parse_common_project_path = staticmethod(LocalInventoryServiceClient.parse_common_project_path) + common_location_path = staticmethod(LocalInventoryServiceClient.common_location_path) + parse_common_location_path = staticmethod(LocalInventoryServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + LocalInventoryServiceAsyncClient: The constructed client. + """ + return LocalInventoryServiceClient.from_service_account_info.__func__(LocalInventoryServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + LocalInventoryServiceAsyncClient: The constructed client. + """ + return LocalInventoryServiceClient.from_service_account_file.__func__(LocalInventoryServiceAsyncClient, 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): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return LocalInventoryServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> LocalInventoryServiceTransport: + """Returns the transport used by the client instance. + + Returns: + LocalInventoryServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = LocalInventoryServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, LocalInventoryServiceTransport, Callable[..., LocalInventoryServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the local inventory service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,LocalInventoryServiceTransport,Callable[..., LocalInventoryServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the LocalInventoryServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = LocalInventoryServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.shopping.merchant.inventories_v1.LocalInventoryServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1.LocalInventoryService", + "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._client._transport, "_credentials") else { + "serviceName": "google.shopping.merchant.inventories.v1.LocalInventoryService", + "credentialsType": None, + } + ) + + async def list_local_inventories(self, + request: Optional[Union[localinventory.ListLocalInventoriesRequest, 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.ListLocalInventoriesAsyncPager: + r"""Lists the ``LocalInventory`` resources for the given product in + your merchant account. The response might contain fewer items + than specified by ``pageSize``. If ``pageToken`` was returned in + previous request, it can be used to obtain additional results. + + ``LocalInventory`` resources are listed per product for a given + account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1 + + async def sample_list_local_inventories(): + # Create a client + client = merchant_inventories_v1.LocalInventoryServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_inventories_v1.ListLocalInventoriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_local_inventories(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_inventories_v1.types.ListLocalInventoriesRequest, dict]]): + The request object. Request message for the ``ListLocalInventories`` method. + parent (:class:`str`): + Required. The ``name`` of the parent product to list + local inventories for. Format: + ``accounts/{account}/products/{product}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.shopping.merchant_inventories_v1.services.local_inventory_service.pagers.ListLocalInventoriesAsyncPager: + Response message for the ListLocalInventories method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, localinventory.ListLocalInventoriesRequest): + request = localinventory.ListLocalInventoriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_local_inventories] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListLocalInventoriesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def insert_local_inventory(self, + request: Optional[Union[localinventory.InsertLocalInventoryRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> localinventory.LocalInventory: + r"""Inserts a ``LocalInventory`` resource to a product in your + merchant account. + + Replaces the full ``LocalInventory`` resource if an entry with + the same + [``storeCode``][google.shopping.merchant.inventories.v1.LocalInventory.store_code] + already exists for the product. + + It might take up to 30 minutes for the new or updated + ``LocalInventory`` resource to appear in products. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1 + + async def sample_insert_local_inventory(): + # Create a client + client = merchant_inventories_v1.LocalInventoryServiceAsyncClient() + + # Initialize request argument(s) + local_inventory = merchant_inventories_v1.LocalInventory() + local_inventory.store_code = "store_code_value" + + request = merchant_inventories_v1.InsertLocalInventoryRequest( + parent="parent_value", + local_inventory=local_inventory, + ) + + # Make the request + response = await client.insert_local_inventory(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_inventories_v1.types.InsertLocalInventoryRequest, dict]]): + The request object. Request message for the ``InsertLocalInventory`` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.shopping.merchant_inventories_v1.types.LocalInventory: + Local inventory information for the product. Represents in-store information + for a specific product at the store specified by + [storeCode][google.shopping.merchant.inventories.v1.LocalInventory.store_code]. + For a list of all accepted attribute values, see the + [local product inventory data + specification](\ https://support.google.com/merchants/answer/3061342). + + """ + # Create or coerce a protobuf request object. + # - 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, localinventory.InsertLocalInventoryRequest): + request = localinventory.InsertLocalInventoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.insert_local_inventory] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_local_inventory(self, + request: Optional[Union[localinventory.DeleteLocalInventoryRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified ``LocalInventory`` from the given product + in your merchant account. It might take a up to an hour for the + ``LocalInventory`` to be deleted from the specific product. Once + you have received a successful delete response, wait for that + period before attempting a delete again. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1 + + async def sample_delete_local_inventory(): + # Create a client + client = merchant_inventories_v1.LocalInventoryServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_inventories_v1.DeleteLocalInventoryRequest( + name="name_value", + ) + + # Make the request + await client.delete_local_inventory(request=request) + + Args: + request (Optional[Union[google.shopping.merchant_inventories_v1.types.DeleteLocalInventoryRequest, dict]]): + The request object. Request message for the ``DeleteLocalInventory`` method. + name (:class:`str`): + Required. The name of the local inventory for the given + product to delete. Format: + ``accounts/{account}/products/{product}/localInventories/{store_code}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, localinventory.DeleteLocalInventoryRequest): + request = localinventory.DeleteLocalInventoryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_local_inventory] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self) -> "LocalInventoryServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ( + "LocalInventoryServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/client.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/client.py new file mode 100644 index 000000000000..716a5957f744 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/client.py @@ -0,0 +1,949 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.shopping.merchant_inventories_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.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 + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.shopping.merchant_inventories_v1.services.local_inventory_service import pagers +from google.shopping.merchant_inventories_v1.types import inventories_common +from google.shopping.merchant_inventories_v1.types import localinventory +from .transports.base import LocalInventoryServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import LocalInventoryServiceGrpcTransport +from .transports.grpc_asyncio import LocalInventoryServiceGrpcAsyncIOTransport +from .transports.rest import LocalInventoryServiceRestTransport + + +class LocalInventoryServiceClientMeta(type): + """Metaclass for the LocalInventoryService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[LocalInventoryServiceTransport]] + _transport_registry["grpc"] = LocalInventoryServiceGrpcTransport + _transport_registry["grpc_asyncio"] = LocalInventoryServiceGrpcAsyncIOTransport + _transport_registry["rest"] = LocalInventoryServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[LocalInventoryServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class LocalInventoryServiceClient(metaclass=LocalInventoryServiceClientMeta): + """Service to manage local inventory for products""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "merchantapi.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "merchantapi.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + LocalInventoryServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + LocalInventoryServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> LocalInventoryServiceTransport: + """Returns the transport used by the client instance. + + Returns: + LocalInventoryServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def local_inventory_path(account: str,product: str,store_code: str,) -> str: + """Returns a fully-qualified local_inventory string.""" + return "accounts/{account}/products/{product}/localInventories/{store_code}".format(account=account, product=product, store_code=store_code, ) + + @staticmethod + def parse_local_inventory_path(path: str) -> Dict[str,str]: + """Parses a local_inventory path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/products/(?P.+?)/localInventories/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + 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: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + 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) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "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 + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_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): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = LocalInventoryServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = LocalInventoryServiceClient._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: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = LocalInventoryServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + 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]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, LocalInventoryServiceTransport, Callable[..., LocalInventoryServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the local inventory service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,LocalInventoryServiceTransport,Callable[..., LocalInventoryServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the LocalInventoryServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + 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) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = LocalInventoryServiceClient._read_environment_variables() + self._client_cert_source = LocalInventoryServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = LocalInventoryServiceClient._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 + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + 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") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, LocalInventoryServiceTransport) + if transport_provided: + # transport is a LocalInventoryServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + 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." + ) + self._transport = cast(LocalInventoryServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + LocalInventoryServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + 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) + + transport_init: Union[Type[LocalInventoryServiceTransport], Callable[..., LocalInventoryServiceTransport]] = ( + LocalInventoryServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., LocalInventoryServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.shopping.merchant.inventories_v1.LocalInventoryServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1.LocalInventoryService", + "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 { + "serviceName": "google.shopping.merchant.inventories.v1.LocalInventoryService", + "credentialsType": None, + } + ) + + def list_local_inventories(self, + request: Optional[Union[localinventory.ListLocalInventoriesRequest, 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.ListLocalInventoriesPager: + r"""Lists the ``LocalInventory`` resources for the given product in + your merchant account. The response might contain fewer items + than specified by ``pageSize``. If ``pageToken`` was returned in + previous request, it can be used to obtain additional results. + + ``LocalInventory`` resources are listed per product for a given + account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1 + + def sample_list_local_inventories(): + # Create a client + client = merchant_inventories_v1.LocalInventoryServiceClient() + + # Initialize request argument(s) + request = merchant_inventories_v1.ListLocalInventoriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_local_inventories(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_inventories_v1.types.ListLocalInventoriesRequest, dict]): + The request object. Request message for the ``ListLocalInventories`` method. + parent (str): + Required. The ``name`` of the parent product to list + local inventories for. Format: + ``accounts/{account}/products/{product}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.shopping.merchant_inventories_v1.services.local_inventory_service.pagers.ListLocalInventoriesPager: + Response message for the ListLocalInventories method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, localinventory.ListLocalInventoriesRequest): + request = localinventory.ListLocalInventoriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_local_inventories] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListLocalInventoriesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def insert_local_inventory(self, + request: Optional[Union[localinventory.InsertLocalInventoryRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> localinventory.LocalInventory: + r"""Inserts a ``LocalInventory`` resource to a product in your + merchant account. + + Replaces the full ``LocalInventory`` resource if an entry with + the same + [``storeCode``][google.shopping.merchant.inventories.v1.LocalInventory.store_code] + already exists for the product. + + It might take up to 30 minutes for the new or updated + ``LocalInventory`` resource to appear in products. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1 + + def sample_insert_local_inventory(): + # Create a client + client = merchant_inventories_v1.LocalInventoryServiceClient() + + # Initialize request argument(s) + local_inventory = merchant_inventories_v1.LocalInventory() + local_inventory.store_code = "store_code_value" + + request = merchant_inventories_v1.InsertLocalInventoryRequest( + parent="parent_value", + local_inventory=local_inventory, + ) + + # Make the request + response = client.insert_local_inventory(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_inventories_v1.types.InsertLocalInventoryRequest, dict]): + The request object. Request message for the ``InsertLocalInventory`` 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: + google.shopping.merchant_inventories_v1.types.LocalInventory: + Local inventory information for the product. Represents in-store information + for a specific product at the store specified by + [storeCode][google.shopping.merchant.inventories.v1.LocalInventory.store_code]. + For a list of all accepted attribute values, see the + [local product inventory data + specification](\ https://support.google.com/merchants/answer/3061342). + + """ + # Create or coerce a protobuf request object. + # - 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, localinventory.InsertLocalInventoryRequest): + request = localinventory.InsertLocalInventoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert_local_inventory] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_local_inventory(self, + request: Optional[Union[localinventory.DeleteLocalInventoryRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified ``LocalInventory`` from the given product + in your merchant account. It might take a up to an hour for the + ``LocalInventory`` to be deleted from the specific product. Once + you have received a successful delete response, wait for that + period before attempting a delete again. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1 + + def sample_delete_local_inventory(): + # Create a client + client = merchant_inventories_v1.LocalInventoryServiceClient() + + # Initialize request argument(s) + request = merchant_inventories_v1.DeleteLocalInventoryRequest( + name="name_value", + ) + + # Make the request + client.delete_local_inventory(request=request) + + Args: + request (Union[google.shopping.merchant_inventories_v1.types.DeleteLocalInventoryRequest, dict]): + The request object. Request message for the ``DeleteLocalInventory`` method. + name (str): + Required. The name of the local inventory for the given + product to delete. Format: + ``accounts/{account}/products/{product}/localInventories/{store_code}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, localinventory.DeleteLocalInventoryRequest): + request = localinventory.DeleteLocalInventoryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_local_inventory] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def __enter__(self) -> "LocalInventoryServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ( + "LocalInventoryServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/pagers.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/pagers.py new file mode 100644 index 000000000000..b25fe0ffc20f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/pagers.py @@ -0,0 +1,166 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from 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] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.shopping.merchant_inventories_v1.types import localinventory + + +class ListLocalInventoriesPager: + """A pager for iterating through ``list_local_inventories`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_inventories_v1.types.ListLocalInventoriesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``local_inventories`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListLocalInventories`` requests and continue to iterate + through the ``local_inventories`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_inventories_v1.types.ListLocalInventoriesResponse` + 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[..., localinventory.ListLocalInventoriesResponse], + request: localinventory.ListLocalInventoriesRequest, + response: localinventory.ListLocalInventoriesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.shopping.merchant_inventories_v1.types.ListLocalInventoriesRequest): + The initial request object. + response (google.shopping.merchant_inventories_v1.types.ListLocalInventoriesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = localinventory.ListLocalInventoriesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[localinventory.ListLocalInventoriesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[localinventory.LocalInventory]: + for page in self.pages: + yield from page.local_inventories + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListLocalInventoriesAsyncPager: + """A pager for iterating through ``list_local_inventories`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_inventories_v1.types.ListLocalInventoriesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``local_inventories`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListLocalInventories`` requests and continue to iterate + through the ``local_inventories`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_inventories_v1.types.ListLocalInventoriesResponse` + 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[localinventory.ListLocalInventoriesResponse]], + request: localinventory.ListLocalInventoriesRequest, + response: localinventory.ListLocalInventoriesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.shopping.merchant_inventories_v1.types.ListLocalInventoriesRequest): + The initial request object. + response (google.shopping.merchant_inventories_v1.types.ListLocalInventoriesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = localinventory.ListLocalInventoriesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[localinventory.ListLocalInventoriesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[localinventory.LocalInventory]: + async def async_generator(): + async for page in self.pages: + for response in page.local_inventories: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/README.rst new file mode 100644 index 000000000000..816e98eb5847 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`LocalInventoryServiceTransport` is the ABC for all transports. +- public child `LocalInventoryServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `LocalInventoryServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseLocalInventoryServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `LocalInventoryServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/__init__.py new file mode 100644 index 000000000000..e1c84f7bce12 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import LocalInventoryServiceTransport +from .grpc import LocalInventoryServiceGrpcTransport +from .grpc_asyncio import LocalInventoryServiceGrpcAsyncIOTransport +from .rest import LocalInventoryServiceRestTransport +from .rest import LocalInventoryServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[LocalInventoryServiceTransport]] +_transport_registry['grpc'] = LocalInventoryServiceGrpcTransport +_transport_registry['grpc_asyncio'] = LocalInventoryServiceGrpcAsyncIOTransport +_transport_registry['rest'] = LocalInventoryServiceRestTransport + +__all__ = ( + 'LocalInventoryServiceTransport', + 'LocalInventoryServiceGrpcTransport', + 'LocalInventoryServiceGrpcAsyncIOTransport', + 'LocalInventoryServiceRestTransport', + 'LocalInventoryServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/base.py new file mode 100644 index 000000000000..abbcbaee2cb8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/base.py @@ -0,0 +1,188 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.shopping.merchant_inventories_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 +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.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1.types import localinventory + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class LocalInventoryServiceTransport(abc.ABC): + """Abstract transport class for LocalInventoryService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/content', + ) + + DEFAULT_HOST: str = 'merchantapi.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: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_local_inventories: gapic_v1.method.wrap_method( + self.list_local_inventories, + default_timeout=None, + client_info=client_info, + ), + self.insert_local_inventory: gapic_v1.method.wrap_method( + self.insert_local_inventory, + default_timeout=None, + client_info=client_info, + ), + self.delete_local_inventory: gapic_v1.method.wrap_method( + self.delete_local_inventory, + 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! + """ + raise NotImplementedError() + + @property + def list_local_inventories(self) -> Callable[ + [localinventory.ListLocalInventoriesRequest], + Union[ + localinventory.ListLocalInventoriesResponse, + Awaitable[localinventory.ListLocalInventoriesResponse] + ]]: + raise NotImplementedError() + + @property + def insert_local_inventory(self) -> Callable[ + [localinventory.InsertLocalInventoryRequest], + Union[ + localinventory.LocalInventory, + Awaitable[localinventory.LocalInventory] + ]]: + raise NotImplementedError() + + @property + def delete_local_inventory(self) -> Callable[ + [localinventory.DeleteLocalInventoryRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'LocalInventoryServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/grpc.py new file mode 100644 index 000000000000..f08af2b10a00 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/grpc.py @@ -0,0 +1,418 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +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 + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1.types import localinventory +from .base import LocalInventoryServiceTransport, 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 + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1.LocalInventoryService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1.LocalInventoryService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class LocalInventoryServiceGrpcTransport(LocalInventoryServiceTransport): + """gRPC backend transport for LocalInventoryService. + + Service to manage local inventory for products + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'merchantapi.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: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'merchantapi.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. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_local_inventories(self) -> Callable[ + [localinventory.ListLocalInventoriesRequest], + localinventory.ListLocalInventoriesResponse]: + r"""Return a callable for the list local inventories method over gRPC. + + Lists the ``LocalInventory`` resources for the given product in + your merchant account. The response might contain fewer items + than specified by ``pageSize``. If ``pageToken`` was returned in + previous request, it can be used to obtain additional results. + + ``LocalInventory`` resources are listed per product for a given + account. + + Returns: + Callable[[~.ListLocalInventoriesRequest], + ~.ListLocalInventoriesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_local_inventories' not in self._stubs: + self._stubs['list_local_inventories'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1.LocalInventoryService/ListLocalInventories', + request_serializer=localinventory.ListLocalInventoriesRequest.serialize, + response_deserializer=localinventory.ListLocalInventoriesResponse.deserialize, + ) + return self._stubs['list_local_inventories'] + + @property + def insert_local_inventory(self) -> Callable[ + [localinventory.InsertLocalInventoryRequest], + localinventory.LocalInventory]: + r"""Return a callable for the insert local inventory method over gRPC. + + Inserts a ``LocalInventory`` resource to a product in your + merchant account. + + Replaces the full ``LocalInventory`` resource if an entry with + the same + [``storeCode``][google.shopping.merchant.inventories.v1.LocalInventory.store_code] + already exists for the product. + + It might take up to 30 minutes for the new or updated + ``LocalInventory`` resource to appear in products. + + Returns: + Callable[[~.InsertLocalInventoryRequest], + ~.LocalInventory]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'insert_local_inventory' not in self._stubs: + self._stubs['insert_local_inventory'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1.LocalInventoryService/InsertLocalInventory', + request_serializer=localinventory.InsertLocalInventoryRequest.serialize, + response_deserializer=localinventory.LocalInventory.deserialize, + ) + return self._stubs['insert_local_inventory'] + + @property + def delete_local_inventory(self) -> Callable[ + [localinventory.DeleteLocalInventoryRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete local inventory method over gRPC. + + Deletes the specified ``LocalInventory`` from the given product + in your merchant account. It might take a up to an hour for the + ``LocalInventory`` to be deleted from the specific product. Once + you have received a successful delete response, wait for that + period before attempting a delete again. + + Returns: + Callable[[~.DeleteLocalInventoryRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_local_inventory' not in self._stubs: + self._stubs['delete_local_inventory'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1.LocalInventoryService/DeleteLocalInventory', + request_serializer=localinventory.DeleteLocalInventoryRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_local_inventory'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'LocalInventoryServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..ab7e499ed9db --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/grpc_asyncio.py @@ -0,0 +1,449 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import pickle +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 retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.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.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1.types import localinventory +from .base import LocalInventoryServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import LocalInventoryServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1.LocalInventoryService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1.LocalInventoryService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class LocalInventoryServiceGrpcAsyncIOTransport(LocalInventoryServiceTransport): + """gRPC AsyncIO backend transport for LocalInventoryService. + + Service to manage local inventory for products + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'merchantapi.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. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'merchantapi.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: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_local_inventories(self) -> Callable[ + [localinventory.ListLocalInventoriesRequest], + Awaitable[localinventory.ListLocalInventoriesResponse]]: + r"""Return a callable for the list local inventories method over gRPC. + + Lists the ``LocalInventory`` resources for the given product in + your merchant account. The response might contain fewer items + than specified by ``pageSize``. If ``pageToken`` was returned in + previous request, it can be used to obtain additional results. + + ``LocalInventory`` resources are listed per product for a given + account. + + Returns: + Callable[[~.ListLocalInventoriesRequest], + Awaitable[~.ListLocalInventoriesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_local_inventories' not in self._stubs: + self._stubs['list_local_inventories'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1.LocalInventoryService/ListLocalInventories', + request_serializer=localinventory.ListLocalInventoriesRequest.serialize, + response_deserializer=localinventory.ListLocalInventoriesResponse.deserialize, + ) + return self._stubs['list_local_inventories'] + + @property + def insert_local_inventory(self) -> Callable[ + [localinventory.InsertLocalInventoryRequest], + Awaitable[localinventory.LocalInventory]]: + r"""Return a callable for the insert local inventory method over gRPC. + + Inserts a ``LocalInventory`` resource to a product in your + merchant account. + + Replaces the full ``LocalInventory`` resource if an entry with + the same + [``storeCode``][google.shopping.merchant.inventories.v1.LocalInventory.store_code] + already exists for the product. + + It might take up to 30 minutes for the new or updated + ``LocalInventory`` resource to appear in products. + + Returns: + Callable[[~.InsertLocalInventoryRequest], + Awaitable[~.LocalInventory]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'insert_local_inventory' not in self._stubs: + self._stubs['insert_local_inventory'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1.LocalInventoryService/InsertLocalInventory', + request_serializer=localinventory.InsertLocalInventoryRequest.serialize, + response_deserializer=localinventory.LocalInventory.deserialize, + ) + return self._stubs['insert_local_inventory'] + + @property + def delete_local_inventory(self) -> Callable[ + [localinventory.DeleteLocalInventoryRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete local inventory method over gRPC. + + Deletes the specified ``LocalInventory`` from the given product + in your merchant account. It might take a up to an hour for the + ``LocalInventory`` to be deleted from the specific product. Once + you have received a successful delete response, wait for that + period before attempting a delete again. + + Returns: + Callable[[~.DeleteLocalInventoryRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_local_inventory' not in self._stubs: + self._stubs['delete_local_inventory'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1.LocalInventoryService/DeleteLocalInventory', + request_serializer=localinventory.DeleteLocalInventoryRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_local_inventory'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_local_inventories: self._wrap_method( + self.list_local_inventories, + default_timeout=None, + client_info=client_info, + ), + self.insert_local_inventory: self._wrap_method( + self.insert_local_inventory, + default_timeout=None, + client_info=client_info, + ), + self.delete_local_inventory: self._wrap_method( + self.delete_local_inventory, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + +__all__ = ( + 'LocalInventoryServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/rest.py new file mode 100644 index 000000000000..70abbea6e70c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/rest.py @@ -0,0 +1,640 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import 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 warnings + + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1.types import localinventory + + +from .rest_base import _BaseLocalInventoryServiceRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class LocalInventoryServiceRestInterceptor: + """Interceptor for LocalInventoryService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the LocalInventoryServiceRestTransport. + + .. code-block:: python + class MyCustomLocalInventoryServiceInterceptor(LocalInventoryServiceRestInterceptor): + def pre_delete_local_inventory(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_insert_local_inventory(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_insert_local_inventory(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_local_inventories(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_local_inventories(self, response): + logging.log(f"Received response: {response}") + return response + + transport = LocalInventoryServiceRestTransport(interceptor=MyCustomLocalInventoryServiceInterceptor()) + client = LocalInventoryServiceClient(transport=transport) + + + """ + def pre_delete_local_inventory(self, request: localinventory.DeleteLocalInventoryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[localinventory.DeleteLocalInventoryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_local_inventory + + Override in a subclass to manipulate the request or metadata + before they are sent to the LocalInventoryService server. + """ + return request, metadata + + def pre_insert_local_inventory(self, request: localinventory.InsertLocalInventoryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[localinventory.InsertLocalInventoryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for insert_local_inventory + + Override in a subclass to manipulate the request or metadata + before they are sent to the LocalInventoryService server. + """ + return request, metadata + + def post_insert_local_inventory(self, response: localinventory.LocalInventory) -> localinventory.LocalInventory: + """Post-rpc interceptor for insert_local_inventory + + DEPRECATED. Please use the `post_insert_local_inventory_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the LocalInventoryService server but before + it is returned to user code. This `post_insert_local_inventory` interceptor runs + before the `post_insert_local_inventory_with_metadata` interceptor. + """ + return response + + def post_insert_local_inventory_with_metadata(self, response: localinventory.LocalInventory, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[localinventory.LocalInventory, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for insert_local_inventory + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the LocalInventoryService server but before it is returned to user code. + + We recommend only using this `post_insert_local_inventory_with_metadata` + interceptor in new development instead of the `post_insert_local_inventory` interceptor. + When both interceptors are used, this `post_insert_local_inventory_with_metadata` interceptor runs after the + `post_insert_local_inventory` interceptor. The (possibly modified) response returned by + `post_insert_local_inventory` will be passed to + `post_insert_local_inventory_with_metadata`. + """ + return response, metadata + + def pre_list_local_inventories(self, request: localinventory.ListLocalInventoriesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[localinventory.ListLocalInventoriesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_local_inventories + + Override in a subclass to manipulate the request or metadata + before they are sent to the LocalInventoryService server. + """ + return request, metadata + + def post_list_local_inventories(self, response: localinventory.ListLocalInventoriesResponse) -> localinventory.ListLocalInventoriesResponse: + """Post-rpc interceptor for list_local_inventories + + DEPRECATED. Please use the `post_list_local_inventories_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the LocalInventoryService server but before + it is returned to user code. This `post_list_local_inventories` interceptor runs + before the `post_list_local_inventories_with_metadata` interceptor. + """ + return response + + def post_list_local_inventories_with_metadata(self, response: localinventory.ListLocalInventoriesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[localinventory.ListLocalInventoriesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_local_inventories + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the LocalInventoryService server but before it is returned to user code. + + We recommend only using this `post_list_local_inventories_with_metadata` + interceptor in new development instead of the `post_list_local_inventories` interceptor. + When both interceptors are used, this `post_list_local_inventories_with_metadata` interceptor runs after the + `post_list_local_inventories` interceptor. The (possibly modified) response returned by + `post_list_local_inventories` will be passed to + `post_list_local_inventories_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class LocalInventoryServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: LocalInventoryServiceRestInterceptor + + +class LocalInventoryServiceRestTransport(_BaseLocalInventoryServiceRestTransport): + """REST backend synchronous transport for LocalInventoryService. + + Service to manage local inventory for products + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'merchantapi.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[LocalInventoryServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or LocalInventoryServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _DeleteLocalInventory(_BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory, LocalInventoryServiceRestStub): + def __hash__(self): + return hash("LocalInventoryServiceRestTransport.DeleteLocalInventory") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: localinventory.DeleteLocalInventoryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete local inventory method over HTTP. + + Args: + request (~.localinventory.DeleteLocalInventoryRequest): + The request object. Request message for the ``DeleteLocalInventory`` 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 = _BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._get_http_options() + + request, metadata = self._interceptor.pre_delete_local_inventory(request, metadata) + transcoded_request = _BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.shopping.merchant.inventories_v1.LocalInventoryServiceClient.DeleteLocalInventory", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1.LocalInventoryService", + "rpcName": "DeleteLocalInventory", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LocalInventoryServiceRestTransport._DeleteLocalInventory._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 _InsertLocalInventory(_BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory, LocalInventoryServiceRestStub): + def __hash__(self): + return hash("LocalInventoryServiceRestTransport.InsertLocalInventory") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: localinventory.InsertLocalInventoryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> localinventory.LocalInventory: + r"""Call the insert local inventory method over HTTP. + + Args: + request (~.localinventory.InsertLocalInventoryRequest): + The request object. Request message for the ``InsertLocalInventory`` 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: + ~.localinventory.LocalInventory: + Local inventory information for the product. Represents + in-store information for a specific product at the store + specified by + [``storeCode``][google.shopping.merchant.inventories.v1.LocalInventory.store_code]. + For a list of all accepted attribute values, see the + `local product inventory data + specification `__. + + """ + + http_options = _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_http_options() + + request, metadata = self._interceptor.pre_insert_local_inventory(request, metadata) + transcoded_request = _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_transcoded_request(http_options, request) + + body = _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.shopping.merchant.inventories_v1.LocalInventoryServiceClient.InsertLocalInventory", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1.LocalInventoryService", + "rpcName": "InsertLocalInventory", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LocalInventoryServiceRestTransport._InsertLocalInventory._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = localinventory.LocalInventory() + pb_resp = localinventory.LocalInventory.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_insert_local_inventory(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_insert_local_inventory_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = localinventory.LocalInventory.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.shopping.merchant.inventories_v1.LocalInventoryServiceClient.insert_local_inventory", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1.LocalInventoryService", + "rpcName": "InsertLocalInventory", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListLocalInventories(_BaseLocalInventoryServiceRestTransport._BaseListLocalInventories, LocalInventoryServiceRestStub): + def __hash__(self): + return hash("LocalInventoryServiceRestTransport.ListLocalInventories") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: localinventory.ListLocalInventoriesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> localinventory.ListLocalInventoriesResponse: + r"""Call the list local inventories method over HTTP. + + Args: + request (~.localinventory.ListLocalInventoriesRequest): + The request object. Request message for the ``ListLocalInventories`` 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: + ~.localinventory.ListLocalInventoriesResponse: + Response message for the ``ListLocalInventories`` + method. + + """ + + http_options = _BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._get_http_options() + + request, metadata = self._interceptor.pre_list_local_inventories(request, metadata) + transcoded_request = _BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.shopping.merchant.inventories_v1.LocalInventoryServiceClient.ListLocalInventories", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1.LocalInventoryService", + "rpcName": "ListLocalInventories", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LocalInventoryServiceRestTransport._ListLocalInventories._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = localinventory.ListLocalInventoriesResponse() + pb_resp = localinventory.ListLocalInventoriesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_local_inventories(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_local_inventories_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = localinventory.ListLocalInventoriesResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.shopping.merchant.inventories_v1.LocalInventoryServiceClient.list_local_inventories", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1.LocalInventoryService", + "rpcName": "ListLocalInventories", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def delete_local_inventory(self) -> Callable[ + [localinventory.DeleteLocalInventoryRequest], + 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._DeleteLocalInventory(self._session, self._host, self._interceptor) # type: ignore + + @property + def insert_local_inventory(self) -> Callable[ + [localinventory.InsertLocalInventoryRequest], + localinventory.LocalInventory]: + # 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._InsertLocalInventory(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_local_inventories(self) -> Callable[ + [localinventory.ListLocalInventoriesRequest], + localinventory.ListLocalInventoriesResponse]: + # 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._ListLocalInventories(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'LocalInventoryServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/rest_base.py new file mode 100644 index 000000000000..d556ef816975 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/rest_base.py @@ -0,0 +1,213 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from .base import LocalInventoryServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1.types import localinventory + + +class _BaseLocalInventoryServiceRestTransport(LocalInventoryServiceTransport): + """Base REST backend transport for LocalInventoryService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'merchantapi.googleapis.com', + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + + class _BaseDeleteLocalInventory: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/inventories/v1/{name=accounts/*/products/*/localInventories/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = localinventory.DeleteLocalInventoryRequest.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(_BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseInsertLocalInventory: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/inventories/v1/{parent=accounts/*/products/*}/localInventories:insert', + 'body': 'local_inventory', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = localinventory.InsertLocalInventoryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListLocalInventories: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/inventories/v1/{parent=accounts/*/products/*}/localInventories', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = localinventory.ListLocalInventoriesRequest.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(_BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseLocalInventoryServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/__init__.py new file mode 100644 index 000000000000..1a0839e5cff5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import RegionalInventoryServiceClient +from .async_client import RegionalInventoryServiceAsyncClient + +__all__ = ( + 'RegionalInventoryServiceClient', + 'RegionalInventoryServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/async_client.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/async_client.py new file mode 100644 index 000000000000..7b299ee89ed2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/async_client.py @@ -0,0 +1,596 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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.shopping.merchant_inventories_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.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + + +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.shopping.merchant_inventories_v1.services.regional_inventory_service import pagers +from google.shopping.merchant_inventories_v1.types import inventories_common +from google.shopping.merchant_inventories_v1.types import regionalinventory +from .transports.base import RegionalInventoryServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import RegionalInventoryServiceGrpcAsyncIOTransport +from .client import RegionalInventoryServiceClient + +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 RegionalInventoryServiceAsyncClient: + """Service to manage regional inventory for products. There is also + separate ``regions`` resource and API to manage regions definitions. + """ + + _client: RegionalInventoryServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = RegionalInventoryServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = RegionalInventoryServiceClient._DEFAULT_UNIVERSE + + regional_inventory_path = staticmethod(RegionalInventoryServiceClient.regional_inventory_path) + parse_regional_inventory_path = staticmethod(RegionalInventoryServiceClient.parse_regional_inventory_path) + common_billing_account_path = staticmethod(RegionalInventoryServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(RegionalInventoryServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(RegionalInventoryServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(RegionalInventoryServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(RegionalInventoryServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(RegionalInventoryServiceClient.parse_common_organization_path) + common_project_path = staticmethod(RegionalInventoryServiceClient.common_project_path) + parse_common_project_path = staticmethod(RegionalInventoryServiceClient.parse_common_project_path) + common_location_path = staticmethod(RegionalInventoryServiceClient.common_location_path) + parse_common_location_path = staticmethod(RegionalInventoryServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RegionalInventoryServiceAsyncClient: The constructed client. + """ + return RegionalInventoryServiceClient.from_service_account_info.__func__(RegionalInventoryServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RegionalInventoryServiceAsyncClient: The constructed client. + """ + return RegionalInventoryServiceClient.from_service_account_file.__func__(RegionalInventoryServiceAsyncClient, 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): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return RegionalInventoryServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> RegionalInventoryServiceTransport: + """Returns the transport used by the client instance. + + Returns: + RegionalInventoryServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = RegionalInventoryServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, RegionalInventoryServiceTransport, Callable[..., RegionalInventoryServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the regional inventory service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,RegionalInventoryServiceTransport,Callable[..., RegionalInventoryServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the RegionalInventoryServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = RegionalInventoryServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.shopping.merchant.inventories_v1.RegionalInventoryServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1.RegionalInventoryService", + "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._client._transport, "_credentials") else { + "serviceName": "google.shopping.merchant.inventories.v1.RegionalInventoryService", + "credentialsType": None, + } + ) + + async def list_regional_inventories(self, + request: Optional[Union[regionalinventory.ListRegionalInventoriesRequest, 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.ListRegionalInventoriesAsyncPager: + r"""Lists the ``RegionalInventory`` resources for the given product + in your merchant account. The response might contain fewer items + than specified by ``pageSize``. If ``pageToken`` was returned in + previous request, it can be used to obtain additional results. + + ``RegionalInventory`` resources are listed per product for a + given account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1 + + async def sample_list_regional_inventories(): + # Create a client + client = merchant_inventories_v1.RegionalInventoryServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_inventories_v1.ListRegionalInventoriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_regional_inventories(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_inventories_v1.types.ListRegionalInventoriesRequest, dict]]): + The request object. Request message for the ``ListRegionalInventories`` + method. + parent (:class:`str`): + Required. The ``name`` of the parent product to list + ``RegionalInventory`` resources for. Format: + ``accounts/{account}/products/{product}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.shopping.merchant_inventories_v1.services.regional_inventory_service.pagers.ListRegionalInventoriesAsyncPager: + Response message for the ListRegionalInventories method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, regionalinventory.ListRegionalInventoriesRequest): + request = regionalinventory.ListRegionalInventoriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_regional_inventories] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListRegionalInventoriesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def insert_regional_inventory(self, + request: Optional[Union[regionalinventory.InsertRegionalInventoryRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regionalinventory.RegionalInventory: + r"""Inserts a ``RegionalInventory`` to a given product in your + merchant account. + + Replaces the full ``RegionalInventory`` resource if an entry + with the same + [``region``][google.shopping.merchant.inventories.v1.RegionalInventory.region] + already exists for the product. + + It might take up to 30 minutes for the new or updated + ``RegionalInventory`` resource to appear in products. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1 + + async def sample_insert_regional_inventory(): + # Create a client + client = merchant_inventories_v1.RegionalInventoryServiceAsyncClient() + + # Initialize request argument(s) + regional_inventory = merchant_inventories_v1.RegionalInventory() + regional_inventory.region = "region_value" + + request = merchant_inventories_v1.InsertRegionalInventoryRequest( + parent="parent_value", + regional_inventory=regional_inventory, + ) + + # Make the request + response = await client.insert_regional_inventory(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_inventories_v1.types.InsertRegionalInventoryRequest, dict]]): + The request object. Request message for the ``InsertRegionalInventory`` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.shopping.merchant_inventories_v1.types.RegionalInventory: + Regional inventory information for the product. Represents specific + information like price and availability for a given + product in a specific + [region][google.shopping.merchant.inventories.v1.RegionalInventory.region]. + For a list of all accepted attribute values, see the + [regional product inventory data + specification](\ https://support.google.com/merchants/answer/9698880). + + """ + # Create or coerce a protobuf request object. + # - 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, regionalinventory.InsertRegionalInventoryRequest): + request = regionalinventory.InsertRegionalInventoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.insert_regional_inventory] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_regional_inventory(self, + request: Optional[Union[regionalinventory.DeleteRegionalInventoryRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified ``RegionalInventory`` resource from the + given product in your merchant account. It might take up to an + hour for the ``RegionalInventory`` to be deleted from the + specific product. Once you have received a successful delete + response, wait for that period before attempting a delete again. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1 + + async def sample_delete_regional_inventory(): + # Create a client + client = merchant_inventories_v1.RegionalInventoryServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_inventories_v1.DeleteRegionalInventoryRequest( + name="name_value", + ) + + # Make the request + await client.delete_regional_inventory(request=request) + + Args: + request (Optional[Union[google.shopping.merchant_inventories_v1.types.DeleteRegionalInventoryRequest, dict]]): + The request object. Request message for the ``DeleteRegionalInventory`` + method. + name (:class:`str`): + Required. The name of the ``RegionalInventory`` resource + to delete. Format: + ``accounts/{account}/products/{product}/regionalInventories/{region}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, regionalinventory.DeleteRegionalInventoryRequest): + request = regionalinventory.DeleteRegionalInventoryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_regional_inventory] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self) -> "RegionalInventoryServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ( + "RegionalInventoryServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/client.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/client.py new file mode 100644 index 000000000000..5726f494c2dd --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/client.py @@ -0,0 +1,955 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.shopping.merchant_inventories_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.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 + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.shopping.merchant_inventories_v1.services.regional_inventory_service import pagers +from google.shopping.merchant_inventories_v1.types import inventories_common +from google.shopping.merchant_inventories_v1.types import regionalinventory +from .transports.base import RegionalInventoryServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import RegionalInventoryServiceGrpcTransport +from .transports.grpc_asyncio import RegionalInventoryServiceGrpcAsyncIOTransport +from .transports.rest import RegionalInventoryServiceRestTransport + + +class RegionalInventoryServiceClientMeta(type): + """Metaclass for the RegionalInventoryService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[RegionalInventoryServiceTransport]] + _transport_registry["grpc"] = RegionalInventoryServiceGrpcTransport + _transport_registry["grpc_asyncio"] = RegionalInventoryServiceGrpcAsyncIOTransport + _transport_registry["rest"] = RegionalInventoryServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[RegionalInventoryServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class RegionalInventoryServiceClient(metaclass=RegionalInventoryServiceClientMeta): + """Service to manage regional inventory for products. There is also + separate ``regions`` resource and API to manage regions definitions. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "merchantapi.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "merchantapi.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RegionalInventoryServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RegionalInventoryServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> RegionalInventoryServiceTransport: + """Returns the transport used by the client instance. + + Returns: + RegionalInventoryServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def regional_inventory_path(account: str,product: str,region: str,) -> str: + """Returns a fully-qualified regional_inventory string.""" + return "accounts/{account}/products/{product}/regionalInventories/{region}".format(account=account, product=product, region=region, ) + + @staticmethod + def parse_regional_inventory_path(path: str) -> Dict[str,str]: + """Parses a regional_inventory path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/products/(?P.+?)/regionalInventories/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + 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: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + 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) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "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 + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_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): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = RegionalInventoryServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = RegionalInventoryServiceClient._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: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = RegionalInventoryServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + 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]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, RegionalInventoryServiceTransport, Callable[..., RegionalInventoryServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the regional inventory service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,RegionalInventoryServiceTransport,Callable[..., RegionalInventoryServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the RegionalInventoryServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + 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) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = RegionalInventoryServiceClient._read_environment_variables() + self._client_cert_source = RegionalInventoryServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = RegionalInventoryServiceClient._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 + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + 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") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, RegionalInventoryServiceTransport) + if transport_provided: + # transport is a RegionalInventoryServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + 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." + ) + self._transport = cast(RegionalInventoryServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + RegionalInventoryServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + 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) + + transport_init: Union[Type[RegionalInventoryServiceTransport], Callable[..., RegionalInventoryServiceTransport]] = ( + RegionalInventoryServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., RegionalInventoryServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.shopping.merchant.inventories_v1.RegionalInventoryServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1.RegionalInventoryService", + "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 { + "serviceName": "google.shopping.merchant.inventories.v1.RegionalInventoryService", + "credentialsType": None, + } + ) + + def list_regional_inventories(self, + request: Optional[Union[regionalinventory.ListRegionalInventoriesRequest, 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.ListRegionalInventoriesPager: + r"""Lists the ``RegionalInventory`` resources for the given product + in your merchant account. The response might contain fewer items + than specified by ``pageSize``. If ``pageToken`` was returned in + previous request, it can be used to obtain additional results. + + ``RegionalInventory`` resources are listed per product for a + given account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1 + + def sample_list_regional_inventories(): + # Create a client + client = merchant_inventories_v1.RegionalInventoryServiceClient() + + # Initialize request argument(s) + request = merchant_inventories_v1.ListRegionalInventoriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_regional_inventories(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_inventories_v1.types.ListRegionalInventoriesRequest, dict]): + The request object. Request message for the ``ListRegionalInventories`` + method. + parent (str): + Required. The ``name`` of the parent product to list + ``RegionalInventory`` resources for. Format: + ``accounts/{account}/products/{product}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.shopping.merchant_inventories_v1.services.regional_inventory_service.pagers.ListRegionalInventoriesPager: + Response message for the ListRegionalInventories method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, regionalinventory.ListRegionalInventoriesRequest): + request = regionalinventory.ListRegionalInventoriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_regional_inventories] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListRegionalInventoriesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def insert_regional_inventory(self, + request: Optional[Union[regionalinventory.InsertRegionalInventoryRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regionalinventory.RegionalInventory: + r"""Inserts a ``RegionalInventory`` to a given product in your + merchant account. + + Replaces the full ``RegionalInventory`` resource if an entry + with the same + [``region``][google.shopping.merchant.inventories.v1.RegionalInventory.region] + already exists for the product. + + It might take up to 30 minutes for the new or updated + ``RegionalInventory`` resource to appear in products. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1 + + def sample_insert_regional_inventory(): + # Create a client + client = merchant_inventories_v1.RegionalInventoryServiceClient() + + # Initialize request argument(s) + regional_inventory = merchant_inventories_v1.RegionalInventory() + regional_inventory.region = "region_value" + + request = merchant_inventories_v1.InsertRegionalInventoryRequest( + parent="parent_value", + regional_inventory=regional_inventory, + ) + + # Make the request + response = client.insert_regional_inventory(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_inventories_v1.types.InsertRegionalInventoryRequest, dict]): + The request object. Request message for the ``InsertRegionalInventory`` + 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: + google.shopping.merchant_inventories_v1.types.RegionalInventory: + Regional inventory information for the product. Represents specific + information like price and availability for a given + product in a specific + [region][google.shopping.merchant.inventories.v1.RegionalInventory.region]. + For a list of all accepted attribute values, see the + [regional product inventory data + specification](\ https://support.google.com/merchants/answer/9698880). + + """ + # Create or coerce a protobuf request object. + # - 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, regionalinventory.InsertRegionalInventoryRequest): + request = regionalinventory.InsertRegionalInventoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert_regional_inventory] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_regional_inventory(self, + request: Optional[Union[regionalinventory.DeleteRegionalInventoryRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified ``RegionalInventory`` resource from the + given product in your merchant account. It might take up to an + hour for the ``RegionalInventory`` to be deleted from the + specific product. Once you have received a successful delete + response, wait for that period before attempting a delete again. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1 + + def sample_delete_regional_inventory(): + # Create a client + client = merchant_inventories_v1.RegionalInventoryServiceClient() + + # Initialize request argument(s) + request = merchant_inventories_v1.DeleteRegionalInventoryRequest( + name="name_value", + ) + + # Make the request + client.delete_regional_inventory(request=request) + + Args: + request (Union[google.shopping.merchant_inventories_v1.types.DeleteRegionalInventoryRequest, dict]): + The request object. Request message for the ``DeleteRegionalInventory`` + method. + name (str): + Required. The name of the ``RegionalInventory`` resource + to delete. Format: + ``accounts/{account}/products/{product}/regionalInventories/{region}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, regionalinventory.DeleteRegionalInventoryRequest): + request = regionalinventory.DeleteRegionalInventoryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_regional_inventory] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def __enter__(self) -> "RegionalInventoryServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ( + "RegionalInventoryServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/pagers.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/pagers.py new file mode 100644 index 000000000000..8cb98b71f403 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/pagers.py @@ -0,0 +1,166 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from 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] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.shopping.merchant_inventories_v1.types import regionalinventory + + +class ListRegionalInventoriesPager: + """A pager for iterating through ``list_regional_inventories`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_inventories_v1.types.ListRegionalInventoriesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``regional_inventories`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListRegionalInventories`` requests and continue to iterate + through the ``regional_inventories`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_inventories_v1.types.ListRegionalInventoriesResponse` + 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[..., regionalinventory.ListRegionalInventoriesResponse], + request: regionalinventory.ListRegionalInventoriesRequest, + response: regionalinventory.ListRegionalInventoriesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.shopping.merchant_inventories_v1.types.ListRegionalInventoriesRequest): + The initial request object. + response (google.shopping.merchant_inventories_v1.types.ListRegionalInventoriesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = regionalinventory.ListRegionalInventoriesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[regionalinventory.ListRegionalInventoriesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[regionalinventory.RegionalInventory]: + for page in self.pages: + yield from page.regional_inventories + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListRegionalInventoriesAsyncPager: + """A pager for iterating through ``list_regional_inventories`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_inventories_v1.types.ListRegionalInventoriesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``regional_inventories`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListRegionalInventories`` requests and continue to iterate + through the ``regional_inventories`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_inventories_v1.types.ListRegionalInventoriesResponse` + 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[regionalinventory.ListRegionalInventoriesResponse]], + request: regionalinventory.ListRegionalInventoriesRequest, + response: regionalinventory.ListRegionalInventoriesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.shopping.merchant_inventories_v1.types.ListRegionalInventoriesRequest): + The initial request object. + response (google.shopping.merchant_inventories_v1.types.ListRegionalInventoriesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = regionalinventory.ListRegionalInventoriesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[regionalinventory.ListRegionalInventoriesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[regionalinventory.RegionalInventory]: + async def async_generator(): + async for page in self.pages: + for response in page.regional_inventories: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/README.rst new file mode 100644 index 000000000000..0b66f48dbd0c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`RegionalInventoryServiceTransport` is the ABC for all transports. +- public child `RegionalInventoryServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `RegionalInventoryServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseRegionalInventoryServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `RegionalInventoryServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/__init__.py new file mode 100644 index 000000000000..b26a37767f11 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import RegionalInventoryServiceTransport +from .grpc import RegionalInventoryServiceGrpcTransport +from .grpc_asyncio import RegionalInventoryServiceGrpcAsyncIOTransport +from .rest import RegionalInventoryServiceRestTransport +from .rest import RegionalInventoryServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[RegionalInventoryServiceTransport]] +_transport_registry['grpc'] = RegionalInventoryServiceGrpcTransport +_transport_registry['grpc_asyncio'] = RegionalInventoryServiceGrpcAsyncIOTransport +_transport_registry['rest'] = RegionalInventoryServiceRestTransport + +__all__ = ( + 'RegionalInventoryServiceTransport', + 'RegionalInventoryServiceGrpcTransport', + 'RegionalInventoryServiceGrpcAsyncIOTransport', + 'RegionalInventoryServiceRestTransport', + 'RegionalInventoryServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/base.py new file mode 100644 index 000000000000..394c2cd125a5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/base.py @@ -0,0 +1,188 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.shopping.merchant_inventories_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 +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.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1.types import regionalinventory + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class RegionalInventoryServiceTransport(abc.ABC): + """Abstract transport class for RegionalInventoryService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/content', + ) + + DEFAULT_HOST: str = 'merchantapi.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: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_regional_inventories: gapic_v1.method.wrap_method( + self.list_regional_inventories, + default_timeout=None, + client_info=client_info, + ), + self.insert_regional_inventory: gapic_v1.method.wrap_method( + self.insert_regional_inventory, + default_timeout=None, + client_info=client_info, + ), + self.delete_regional_inventory: gapic_v1.method.wrap_method( + self.delete_regional_inventory, + 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! + """ + raise NotImplementedError() + + @property + def list_regional_inventories(self) -> Callable[ + [regionalinventory.ListRegionalInventoriesRequest], + Union[ + regionalinventory.ListRegionalInventoriesResponse, + Awaitable[regionalinventory.ListRegionalInventoriesResponse] + ]]: + raise NotImplementedError() + + @property + def insert_regional_inventory(self) -> Callable[ + [regionalinventory.InsertRegionalInventoryRequest], + Union[ + regionalinventory.RegionalInventory, + Awaitable[regionalinventory.RegionalInventory] + ]]: + raise NotImplementedError() + + @property + def delete_regional_inventory(self) -> Callable[ + [regionalinventory.DeleteRegionalInventoryRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'RegionalInventoryServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/grpc.py new file mode 100644 index 000000000000..40d2ac39f2b5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/grpc.py @@ -0,0 +1,419 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +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 + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1.types import regionalinventory +from .base import RegionalInventoryServiceTransport, 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 + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1.RegionalInventoryService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1.RegionalInventoryService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class RegionalInventoryServiceGrpcTransport(RegionalInventoryServiceTransport): + """gRPC backend transport for RegionalInventoryService. + + Service to manage regional inventory for products. There is also + separate ``regions`` resource and API to manage regions definitions. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'merchantapi.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: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'merchantapi.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. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_regional_inventories(self) -> Callable[ + [regionalinventory.ListRegionalInventoriesRequest], + regionalinventory.ListRegionalInventoriesResponse]: + r"""Return a callable for the list regional inventories method over gRPC. + + Lists the ``RegionalInventory`` resources for the given product + in your merchant account. The response might contain fewer items + than specified by ``pageSize``. If ``pageToken`` was returned in + previous request, it can be used to obtain additional results. + + ``RegionalInventory`` resources are listed per product for a + given account. + + Returns: + Callable[[~.ListRegionalInventoriesRequest], + ~.ListRegionalInventoriesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_regional_inventories' not in self._stubs: + self._stubs['list_regional_inventories'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1.RegionalInventoryService/ListRegionalInventories', + request_serializer=regionalinventory.ListRegionalInventoriesRequest.serialize, + response_deserializer=regionalinventory.ListRegionalInventoriesResponse.deserialize, + ) + return self._stubs['list_regional_inventories'] + + @property + def insert_regional_inventory(self) -> Callable[ + [regionalinventory.InsertRegionalInventoryRequest], + regionalinventory.RegionalInventory]: + r"""Return a callable for the insert regional inventory method over gRPC. + + Inserts a ``RegionalInventory`` to a given product in your + merchant account. + + Replaces the full ``RegionalInventory`` resource if an entry + with the same + [``region``][google.shopping.merchant.inventories.v1.RegionalInventory.region] + already exists for the product. + + It might take up to 30 minutes for the new or updated + ``RegionalInventory`` resource to appear in products. + + Returns: + Callable[[~.InsertRegionalInventoryRequest], + ~.RegionalInventory]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'insert_regional_inventory' not in self._stubs: + self._stubs['insert_regional_inventory'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1.RegionalInventoryService/InsertRegionalInventory', + request_serializer=regionalinventory.InsertRegionalInventoryRequest.serialize, + response_deserializer=regionalinventory.RegionalInventory.deserialize, + ) + return self._stubs['insert_regional_inventory'] + + @property + def delete_regional_inventory(self) -> Callable[ + [regionalinventory.DeleteRegionalInventoryRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete regional inventory method over gRPC. + + Deletes the specified ``RegionalInventory`` resource from the + given product in your merchant account. It might take up to an + hour for the ``RegionalInventory`` to be deleted from the + specific product. Once you have received a successful delete + response, wait for that period before attempting a delete again. + + Returns: + Callable[[~.DeleteRegionalInventoryRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_regional_inventory' not in self._stubs: + self._stubs['delete_regional_inventory'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1.RegionalInventoryService/DeleteRegionalInventory', + request_serializer=regionalinventory.DeleteRegionalInventoryRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_regional_inventory'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'RegionalInventoryServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..334c40aab377 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/grpc_asyncio.py @@ -0,0 +1,450 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import pickle +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 retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.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.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1.types import regionalinventory +from .base import RegionalInventoryServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import RegionalInventoryServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1.RegionalInventoryService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1.RegionalInventoryService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class RegionalInventoryServiceGrpcAsyncIOTransport(RegionalInventoryServiceTransport): + """gRPC AsyncIO backend transport for RegionalInventoryService. + + Service to manage regional inventory for products. There is also + separate ``regions`` resource and API to manage regions definitions. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'merchantapi.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. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'merchantapi.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: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_regional_inventories(self) -> Callable[ + [regionalinventory.ListRegionalInventoriesRequest], + Awaitable[regionalinventory.ListRegionalInventoriesResponse]]: + r"""Return a callable for the list regional inventories method over gRPC. + + Lists the ``RegionalInventory`` resources for the given product + in your merchant account. The response might contain fewer items + than specified by ``pageSize``. If ``pageToken`` was returned in + previous request, it can be used to obtain additional results. + + ``RegionalInventory`` resources are listed per product for a + given account. + + Returns: + Callable[[~.ListRegionalInventoriesRequest], + Awaitable[~.ListRegionalInventoriesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_regional_inventories' not in self._stubs: + self._stubs['list_regional_inventories'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1.RegionalInventoryService/ListRegionalInventories', + request_serializer=regionalinventory.ListRegionalInventoriesRequest.serialize, + response_deserializer=regionalinventory.ListRegionalInventoriesResponse.deserialize, + ) + return self._stubs['list_regional_inventories'] + + @property + def insert_regional_inventory(self) -> Callable[ + [regionalinventory.InsertRegionalInventoryRequest], + Awaitable[regionalinventory.RegionalInventory]]: + r"""Return a callable for the insert regional inventory method over gRPC. + + Inserts a ``RegionalInventory`` to a given product in your + merchant account. + + Replaces the full ``RegionalInventory`` resource if an entry + with the same + [``region``][google.shopping.merchant.inventories.v1.RegionalInventory.region] + already exists for the product. + + It might take up to 30 minutes for the new or updated + ``RegionalInventory`` resource to appear in products. + + Returns: + Callable[[~.InsertRegionalInventoryRequest], + Awaitable[~.RegionalInventory]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'insert_regional_inventory' not in self._stubs: + self._stubs['insert_regional_inventory'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1.RegionalInventoryService/InsertRegionalInventory', + request_serializer=regionalinventory.InsertRegionalInventoryRequest.serialize, + response_deserializer=regionalinventory.RegionalInventory.deserialize, + ) + return self._stubs['insert_regional_inventory'] + + @property + def delete_regional_inventory(self) -> Callable[ + [regionalinventory.DeleteRegionalInventoryRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete regional inventory method over gRPC. + + Deletes the specified ``RegionalInventory`` resource from the + given product in your merchant account. It might take up to an + hour for the ``RegionalInventory`` to be deleted from the + specific product. Once you have received a successful delete + response, wait for that period before attempting a delete again. + + Returns: + Callable[[~.DeleteRegionalInventoryRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_regional_inventory' not in self._stubs: + self._stubs['delete_regional_inventory'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1.RegionalInventoryService/DeleteRegionalInventory', + request_serializer=regionalinventory.DeleteRegionalInventoryRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_regional_inventory'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_regional_inventories: self._wrap_method( + self.list_regional_inventories, + default_timeout=None, + client_info=client_info, + ), + self.insert_regional_inventory: self._wrap_method( + self.insert_regional_inventory, + default_timeout=None, + client_info=client_info, + ), + self.delete_regional_inventory: self._wrap_method( + self.delete_regional_inventory, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + +__all__ = ( + 'RegionalInventoryServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/rest.py new file mode 100644 index 000000000000..d9411c847f18 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/rest.py @@ -0,0 +1,644 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import 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 warnings + + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1.types import regionalinventory + + +from .rest_base import _BaseRegionalInventoryServiceRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class RegionalInventoryServiceRestInterceptor: + """Interceptor for RegionalInventoryService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the RegionalInventoryServiceRestTransport. + + .. code-block:: python + class MyCustomRegionalInventoryServiceInterceptor(RegionalInventoryServiceRestInterceptor): + def pre_delete_regional_inventory(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_insert_regional_inventory(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_insert_regional_inventory(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_regional_inventories(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_regional_inventories(self, response): + logging.log(f"Received response: {response}") + return response + + transport = RegionalInventoryServiceRestTransport(interceptor=MyCustomRegionalInventoryServiceInterceptor()) + client = RegionalInventoryServiceClient(transport=transport) + + + """ + def pre_delete_regional_inventory(self, request: regionalinventory.DeleteRegionalInventoryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regionalinventory.DeleteRegionalInventoryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_regional_inventory + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionalInventoryService server. + """ + return request, metadata + + def pre_insert_regional_inventory(self, request: regionalinventory.InsertRegionalInventoryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regionalinventory.InsertRegionalInventoryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for insert_regional_inventory + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionalInventoryService server. + """ + return request, metadata + + def post_insert_regional_inventory(self, response: regionalinventory.RegionalInventory) -> regionalinventory.RegionalInventory: + """Post-rpc interceptor for insert_regional_inventory + + DEPRECATED. Please use the `post_insert_regional_inventory_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the RegionalInventoryService server but before + it is returned to user code. This `post_insert_regional_inventory` interceptor runs + before the `post_insert_regional_inventory_with_metadata` interceptor. + """ + return response + + def post_insert_regional_inventory_with_metadata(self, response: regionalinventory.RegionalInventory, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regionalinventory.RegionalInventory, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for insert_regional_inventory + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the RegionalInventoryService server but before it is returned to user code. + + We recommend only using this `post_insert_regional_inventory_with_metadata` + interceptor in new development instead of the `post_insert_regional_inventory` interceptor. + When both interceptors are used, this `post_insert_regional_inventory_with_metadata` interceptor runs after the + `post_insert_regional_inventory` interceptor. The (possibly modified) response returned by + `post_insert_regional_inventory` will be passed to + `post_insert_regional_inventory_with_metadata`. + """ + return response, metadata + + def pre_list_regional_inventories(self, request: regionalinventory.ListRegionalInventoriesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regionalinventory.ListRegionalInventoriesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_regional_inventories + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionalInventoryService server. + """ + return request, metadata + + def post_list_regional_inventories(self, response: regionalinventory.ListRegionalInventoriesResponse) -> regionalinventory.ListRegionalInventoriesResponse: + """Post-rpc interceptor for list_regional_inventories + + DEPRECATED. Please use the `post_list_regional_inventories_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the RegionalInventoryService server but before + it is returned to user code. This `post_list_regional_inventories` interceptor runs + before the `post_list_regional_inventories_with_metadata` interceptor. + """ + return response + + def post_list_regional_inventories_with_metadata(self, response: regionalinventory.ListRegionalInventoriesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regionalinventory.ListRegionalInventoriesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_regional_inventories + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the RegionalInventoryService server but before it is returned to user code. + + We recommend only using this `post_list_regional_inventories_with_metadata` + interceptor in new development instead of the `post_list_regional_inventories` interceptor. + When both interceptors are used, this `post_list_regional_inventories_with_metadata` interceptor runs after the + `post_list_regional_inventories` interceptor. The (possibly modified) response returned by + `post_list_regional_inventories` will be passed to + `post_list_regional_inventories_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class RegionalInventoryServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: RegionalInventoryServiceRestInterceptor + + +class RegionalInventoryServiceRestTransport(_BaseRegionalInventoryServiceRestTransport): + """REST backend synchronous transport for RegionalInventoryService. + + Service to manage regional inventory for products. There is also + separate ``regions`` resource and API to manage regions definitions. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'merchantapi.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[RegionalInventoryServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or RegionalInventoryServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _DeleteRegionalInventory(_BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory, RegionalInventoryServiceRestStub): + def __hash__(self): + return hash("RegionalInventoryServiceRestTransport.DeleteRegionalInventory") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: regionalinventory.DeleteRegionalInventoryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete regional inventory method over HTTP. + + Args: + request (~.regionalinventory.DeleteRegionalInventoryRequest): + The request object. Request message for the ``DeleteRegionalInventory`` + 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 = _BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._get_http_options() + + request, metadata = self._interceptor.pre_delete_regional_inventory(request, metadata) + transcoded_request = _BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.shopping.merchant.inventories_v1.RegionalInventoryServiceClient.DeleteRegionalInventory", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1.RegionalInventoryService", + "rpcName": "DeleteRegionalInventory", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionalInventoryServiceRestTransport._DeleteRegionalInventory._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 _InsertRegionalInventory(_BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory, RegionalInventoryServiceRestStub): + def __hash__(self): + return hash("RegionalInventoryServiceRestTransport.InsertRegionalInventory") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: regionalinventory.InsertRegionalInventoryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> regionalinventory.RegionalInventory: + r"""Call the insert regional inventory method over HTTP. + + Args: + request (~.regionalinventory.InsertRegionalInventoryRequest): + The request object. Request message for the ``InsertRegionalInventory`` + 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: + ~.regionalinventory.RegionalInventory: + Regional inventory information for the product. + Represents specific information like price and + availability for a given product in a specific + [``region``][google.shopping.merchant.inventories.v1.RegionalInventory.region]. + For a list of all accepted attribute values, see the + `regional product inventory data + specification `__. + + """ + + http_options = _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_http_options() + + request, metadata = self._interceptor.pre_insert_regional_inventory(request, metadata) + transcoded_request = _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_transcoded_request(http_options, request) + + body = _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.shopping.merchant.inventories_v1.RegionalInventoryServiceClient.InsertRegionalInventory", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1.RegionalInventoryService", + "rpcName": "InsertRegionalInventory", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionalInventoryServiceRestTransport._InsertRegionalInventory._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = regionalinventory.RegionalInventory() + pb_resp = regionalinventory.RegionalInventory.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_insert_regional_inventory(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_insert_regional_inventory_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = regionalinventory.RegionalInventory.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.shopping.merchant.inventories_v1.RegionalInventoryServiceClient.insert_regional_inventory", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1.RegionalInventoryService", + "rpcName": "InsertRegionalInventory", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListRegionalInventories(_BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories, RegionalInventoryServiceRestStub): + def __hash__(self): + return hash("RegionalInventoryServiceRestTransport.ListRegionalInventories") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: regionalinventory.ListRegionalInventoriesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> regionalinventory.ListRegionalInventoriesResponse: + r"""Call the list regional inventories method over HTTP. + + Args: + request (~.regionalinventory.ListRegionalInventoriesRequest): + The request object. Request message for the ``ListRegionalInventories`` + 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: + ~.regionalinventory.ListRegionalInventoriesResponse: + Response message for the ``ListRegionalInventories`` + method. + + """ + + http_options = _BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._get_http_options() + + request, metadata = self._interceptor.pre_list_regional_inventories(request, metadata) + transcoded_request = _BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.shopping.merchant.inventories_v1.RegionalInventoryServiceClient.ListRegionalInventories", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1.RegionalInventoryService", + "rpcName": "ListRegionalInventories", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionalInventoryServiceRestTransport._ListRegionalInventories._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = regionalinventory.ListRegionalInventoriesResponse() + pb_resp = regionalinventory.ListRegionalInventoriesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_regional_inventories(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_regional_inventories_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = regionalinventory.ListRegionalInventoriesResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.shopping.merchant.inventories_v1.RegionalInventoryServiceClient.list_regional_inventories", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1.RegionalInventoryService", + "rpcName": "ListRegionalInventories", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def delete_regional_inventory(self) -> Callable[ + [regionalinventory.DeleteRegionalInventoryRequest], + 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._DeleteRegionalInventory(self._session, self._host, self._interceptor) # type: ignore + + @property + def insert_regional_inventory(self) -> Callable[ + [regionalinventory.InsertRegionalInventoryRequest], + regionalinventory.RegionalInventory]: + # 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._InsertRegionalInventory(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_regional_inventories(self) -> Callable[ + [regionalinventory.ListRegionalInventoriesRequest], + regionalinventory.ListRegionalInventoriesResponse]: + # 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._ListRegionalInventories(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'RegionalInventoryServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/rest_base.py new file mode 100644 index 000000000000..286531c5fe10 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/rest_base.py @@ -0,0 +1,213 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from .base import RegionalInventoryServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1.types import regionalinventory + + +class _BaseRegionalInventoryServiceRestTransport(RegionalInventoryServiceTransport): + """Base REST backend transport for RegionalInventoryService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'merchantapi.googleapis.com', + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + + class _BaseDeleteRegionalInventory: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/inventories/v1/{name=accounts/*/products/*/regionalInventories/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = regionalinventory.DeleteRegionalInventoryRequest.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(_BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseInsertRegionalInventory: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/inventories/v1/{parent=accounts/*/products/*}/regionalInventories:insert', + 'body': 'regional_inventory', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = regionalinventory.InsertRegionalInventoryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListRegionalInventories: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/inventories/v1/{parent=accounts/*/products/*}/regionalInventories', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = regionalinventory.ListRegionalInventoriesRequest.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(_BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseRegionalInventoryServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/__init__.py new file mode 100644 index 000000000000..b6ff0b1dac5e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/__init__.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .inventories_common import ( + LocalInventoryAttributes, + RegionalInventoryAttributes, +) +from .localinventory import ( + DeleteLocalInventoryRequest, + InsertLocalInventoryRequest, + ListLocalInventoriesRequest, + ListLocalInventoriesResponse, + LocalInventory, +) +from .regionalinventory import ( + DeleteRegionalInventoryRequest, + InsertRegionalInventoryRequest, + ListRegionalInventoriesRequest, + ListRegionalInventoriesResponse, + RegionalInventory, +) + +__all__ = ( + 'LocalInventoryAttributes', + 'RegionalInventoryAttributes', + 'DeleteLocalInventoryRequest', + 'InsertLocalInventoryRequest', + 'ListLocalInventoriesRequest', + 'ListLocalInventoriesResponse', + 'LocalInventory', + 'DeleteRegionalInventoryRequest', + 'InsertRegionalInventoryRequest', + 'ListRegionalInventoriesRequest', + 'ListRegionalInventoriesResponse', + 'RegionalInventory', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/inventories_common.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/inventories_common.py new file mode 100644 index 000000000000..76aa3a64cb07 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/inventories_common.py @@ -0,0 +1,281 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.shopping.type.types import types +from google.type import interval_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.inventories.v1', + manifest={ + 'LocalInventoryAttributes', + 'RegionalInventoryAttributes', + }, +) + + +class LocalInventoryAttributes(proto.Message): + r"""Local inventory attributes. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + price (google.shopping.type.types.Price): + Optional. Price of the product at this store. + sale_price (google.shopping.type.types.Price): + Optional. Sale price of the product at this store. Mandatory + if + [``salePriceEffectiveDate``][LocalInventory.sale_price_effective_date] + is defined. + sale_price_effective_date (google.type.interval_pb2.Interval): + Optional. The ``TimePeriod`` of the sale at this store. + availability (google.shopping.merchant_inventories_v1.types.LocalInventoryAttributes.Availability): + `Availability `__ + of the product at this store. + + This field is a member of `oneof`_ ``_availability``. + quantity (int): + Optional. Quantity of the product available + at this store. Must be greater than or equal to + zero. + + This field is a member of `oneof`_ ``_quantity``. + pickup_method (google.shopping.merchant_inventories_v1.types.LocalInventoryAttributes.PickupMethod): + Optional. Supported `pickup + method `__ + for this product. Unless the value is ``"not supported"``, + this field must be submitted together with ``pickupSla``. + + This field is a member of `oneof`_ ``_pickup_method``. + pickup_sla (google.shopping.merchant_inventories_v1.types.LocalInventoryAttributes.PickupSla): + Optional. Relative time period from the order date for an + order for this product, from this store, to be ready for + pickup. Must be submitted with ``pickupMethod``. See more + details + `here `__. + + This field is a member of `oneof`_ ``_pickup_sla``. + instore_product_location (str): + Optional. Location of the product inside the + store. Maximum length is 20 bytes. + + This field is a member of `oneof`_ ``_instore_product_location``. + """ + class Availability(proto.Enum): + r"""`Availability `__ + of the product at this store. + + Values: + LOCAL_INVENTORY_AVAILABILITY_UNSPECIFIED (0): + Indicates that the availability is + unspecified. + IN_STOCK (1): + Indicates that the product is in stock. + LIMITED_AVAILABILITY (2): + Indicates that the product is out of stock. + ON_DISPLAY_TO_ORDER (3): + Indicates that the product is on display to + order. + OUT_OF_STOCK (4): + Indicates that the product is out of stock. + """ + LOCAL_INVENTORY_AVAILABILITY_UNSPECIFIED = 0 + IN_STOCK = 1 + LIMITED_AVAILABILITY = 2 + ON_DISPLAY_TO_ORDER = 3 + OUT_OF_STOCK = 4 + + class PickupMethod(proto.Enum): + r"""Supported `pickup + method `__ for + this product. Unless the value is ``"not supported"``, this field + must be submitted together with ``pickupSla``. + + Values: + PICKUP_METHOD_UNSPECIFIED (0): + Indicates that the pickup method is + unspecified. + BUY (1): + Indicates that the pickup method is Buy. + RESERVE (2): + Indicates that the pickup method is Reserve. + SHIP_TO_STORE (3): + Indicates that the pickup method is Ship to + store. + NOT_SUPPORTED (4): + Indicates that the pickup method is not + supported. + """ + PICKUP_METHOD_UNSPECIFIED = 0 + BUY = 1 + RESERVE = 2 + SHIP_TO_STORE = 3 + NOT_SUPPORTED = 4 + + class PickupSla(proto.Enum): + r"""Relative time period from the order date for an order for this + product, from this store, to be ready for pickup. Must be submitted + with ``pickupMethod``. See more details + `here `__. + + Values: + PICKUP_SLA_UNSPECIFIED (0): + Indicates that the pickup SLA is unspecified. + SAME_DAY (1): + Indicates that the pickup SLA is same day. + NEXT_DAY (2): + Indicates that the pickup SLA is next day. + TWO_DAY (3): + Indicates that the pickup SLA is two days. + THREE_DAY (4): + Indicates that the pickup SLA is three days. + FOUR_DAY (5): + Indicates that the pickup SLA is four days. + FIVE_DAY (6): + Indicates that the pickup SLA is five days. + SIX_DAY (7): + Indicates that the pickup SLA is six days. + SEVEN_DAY (8): + Indicates that the pickup SLA is seven days. + MULTI_WEEK (9): + Indicates that the pickup SLA is multi-week. + """ + PICKUP_SLA_UNSPECIFIED = 0 + SAME_DAY = 1 + NEXT_DAY = 2 + TWO_DAY = 3 + THREE_DAY = 4 + FOUR_DAY = 5 + FIVE_DAY = 6 + SIX_DAY = 7 + SEVEN_DAY = 8 + MULTI_WEEK = 9 + + price: types.Price = proto.Field( + proto.MESSAGE, + number=1, + message=types.Price, + ) + sale_price: types.Price = proto.Field( + proto.MESSAGE, + number=2, + message=types.Price, + ) + sale_price_effective_date: interval_pb2.Interval = proto.Field( + proto.MESSAGE, + number=3, + message=interval_pb2.Interval, + ) + availability: Availability = proto.Field( + proto.ENUM, + number=4, + optional=True, + enum=Availability, + ) + quantity: int = proto.Field( + proto.INT64, + number=5, + optional=True, + ) + pickup_method: PickupMethod = proto.Field( + proto.ENUM, + number=6, + optional=True, + enum=PickupMethod, + ) + pickup_sla: PickupSla = proto.Field( + proto.ENUM, + number=7, + optional=True, + enum=PickupSla, + ) + instore_product_location: str = proto.Field( + proto.STRING, + number=8, + optional=True, + ) + + +class RegionalInventoryAttributes(proto.Message): + r"""Regional inventory attributes. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + price (google.shopping.type.types.Price): + Optional. Price of the product in this + region. + sale_price (google.shopping.type.types.Price): + Optional. Sale price of the product in this region. + Mandatory if + [``salePriceEffectiveDate``][RegionalInventory.sale_price_effective_date] + is defined. + sale_price_effective_date (google.type.interval_pb2.Interval): + Optional. The ``TimePeriod`` of the sale price in this + region. + availability (google.shopping.merchant_inventories_v1.types.RegionalInventoryAttributes.Availability): + Optional. + `Availability `__ + of the product in this region. + + This field is a member of `oneof`_ ``_availability``. + """ + class Availability(proto.Enum): + r"""`Availability `__ + of the product in this region. + + Values: + REGIONAL_INVENTORY_AVAILABILITY_UNSPECIFIED (0): + Indicates that the availability is + unspecified. + IN_STOCK (1): + Indicates that the product is in stock. + OUT_OF_STOCK (2): + Indicates that the product is out of stock. + """ + REGIONAL_INVENTORY_AVAILABILITY_UNSPECIFIED = 0 + IN_STOCK = 1 + OUT_OF_STOCK = 2 + + price: types.Price = proto.Field( + proto.MESSAGE, + number=1, + message=types.Price, + ) + sale_price: types.Price = proto.Field( + proto.MESSAGE, + number=2, + message=types.Price, + ) + sale_price_effective_date: interval_pb2.Interval = proto.Field( + proto.MESSAGE, + number=3, + message=interval_pb2.Interval, + ) + availability: Availability = proto.Field( + proto.ENUM, + number=4, + optional=True, + enum=Availability, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/localinventory.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/localinventory.py new file mode 100644 index 000000000000..2cbebf9dbf5a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/localinventory.py @@ -0,0 +1,196 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.shopping.merchant_inventories_v1.types import inventories_common + + +__protobuf__ = proto.module( + package='google.shopping.merchant.inventories.v1', + manifest={ + 'LocalInventory', + 'ListLocalInventoriesRequest', + 'ListLocalInventoriesResponse', + 'InsertLocalInventoryRequest', + 'DeleteLocalInventoryRequest', + }, +) + + +class LocalInventory(proto.Message): + r"""Local inventory information for the product. Represents in-store + information for a specific product at the store specified by + [``storeCode``][google.shopping.merchant.inventories.v1.LocalInventory.store_code]. + For a list of all accepted attribute values, see the `local product + inventory data + specification `__. + + Attributes: + name (str): + Output only. The name of the ``LocalInventory`` resource. + Format: + ``accounts/{account}/products/{product}/localInventories/{store_code}`` + account (int): + Output only. The account that owns the + product. This field will be ignored if set by + the client. + store_code (str): + Required. Immutable. Store code (the store ID from your + Business Profile) of the physical store the product is sold + in. See the `Local product inventory data + specification `__ + for more information. + local_inventory_attributes (google.shopping.merchant_inventories_v1.types.LocalInventoryAttributes): + Optional. A list of local inventory + attributes. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + account: int = proto.Field( + proto.INT64, + number=2, + ) + store_code: str = proto.Field( + proto.STRING, + number=3, + ) + local_inventory_attributes: inventories_common.LocalInventoryAttributes = proto.Field( + proto.MESSAGE, + number=14, + message=inventories_common.LocalInventoryAttributes, + ) + + +class ListLocalInventoriesRequest(proto.Message): + r"""Request message for the ``ListLocalInventories`` method. + + Attributes: + parent (str): + Required. The ``name`` of the parent product to list local + inventories for. Format: + ``accounts/{account}/products/{product}`` + page_size (int): + The maximum number of ``LocalInventory`` resources for the + given product to return. The service returns fewer than this + value if the number of inventories for the given product is + less that than the ``pageSize``. The default value is 25000. + The maximum value is 25000; If a value higher than the + maximum is specified, then the ``pageSize`` will default to + the maximum + page_token (str): + A page token, received from a previous + ``ListLocalInventories`` call. Provide the page token to + retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListLocalInventories`` must match the call that provided + the page token. The token returned as + [nextPageToken][google.shopping.merchant.inventories.v1.ListLocalInventoriesResponse.next_page_token] + in the response to the previous request. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListLocalInventoriesResponse(proto.Message): + r"""Response message for the ``ListLocalInventories`` method. + + Attributes: + local_inventories (MutableSequence[google.shopping.merchant_inventories_v1.types.LocalInventory]): + The ``LocalInventory`` resources for the given product from + the specified account. + next_page_token (str): + A token, which can be sent as ``pageToken`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + local_inventories: MutableSequence['LocalInventory'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='LocalInventory', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class InsertLocalInventoryRequest(proto.Message): + r"""Request message for the ``InsertLocalInventory`` method. + + Attributes: + parent (str): + Required. The account and product where this inventory will + be inserted. Format: + ``accounts/{account}/products/{product}`` + local_inventory (google.shopping.merchant_inventories_v1.types.LocalInventory): + Required. Local inventory information of the product. If the + product already has a ``LocalInventory`` resource for the + same ``storeCode``, full replacement of the + ``LocalInventory`` resource is performed. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + local_inventory: 'LocalInventory' = proto.Field( + proto.MESSAGE, + number=2, + message='LocalInventory', + ) + + +class DeleteLocalInventoryRequest(proto.Message): + r"""Request message for the ``DeleteLocalInventory`` method. + + Attributes: + name (str): + Required. The name of the local inventory for the given + product to delete. Format: + ``accounts/{account}/products/{product}/localInventories/{store_code}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/regionalinventory.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/regionalinventory.py new file mode 100644 index 000000000000..ecf87fc3b24e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/regionalinventory.py @@ -0,0 +1,197 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.shopping.merchant_inventories_v1.types import inventories_common + + +__protobuf__ = proto.module( + package='google.shopping.merchant.inventories.v1', + manifest={ + 'RegionalInventory', + 'ListRegionalInventoriesRequest', + 'ListRegionalInventoriesResponse', + 'InsertRegionalInventoryRequest', + 'DeleteRegionalInventoryRequest', + }, +) + + +class RegionalInventory(proto.Message): + r"""Regional inventory information for the product. Represents specific + information like price and availability for a given product in a + specific + [``region``][google.shopping.merchant.inventories.v1.RegionalInventory.region]. + For a list of all accepted attribute values, see the `regional + product inventory data + specification `__. + + Attributes: + name (str): + Output only. The name of the ``RegionalInventory`` resource. + Format: + ``{regional_inventory.name=accounts/{account}/products/{product}/regionalInventories/{region}`` + account (int): + Output only. The account that owns the + product. This field will be ignored if set by + the client. + region (str): + Required. Immutable. ID of the region for this + ``RegionalInventory`` resource. See the `Regional + availability and + pricing `__ + for more details. + regional_inventory_attributes (google.shopping.merchant_inventories_v1.types.RegionalInventoryAttributes): + Optional. A list of regional inventory + attributes. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + account: int = proto.Field( + proto.INT64, + number=2, + ) + region: str = proto.Field( + proto.STRING, + number=3, + ) + regional_inventory_attributes: inventories_common.RegionalInventoryAttributes = proto.Field( + proto.MESSAGE, + number=9, + message=inventories_common.RegionalInventoryAttributes, + ) + + +class ListRegionalInventoriesRequest(proto.Message): + r"""Request message for the ``ListRegionalInventories`` method. + + Attributes: + parent (str): + Required. The ``name`` of the parent product to list + ``RegionalInventory`` resources for. Format: + ``accounts/{account}/products/{product}`` + page_size (int): + The maximum number of ``RegionalInventory`` resources for + the given product to return. The service returns fewer than + this value if the number of inventories for the given + product is less that than the ``pageSize``. The default + value is 25000. The maximum value is 100000; If a value + higher than the maximum is specified, then the ``pageSize`` + will default to the maximum. + page_token (str): + A page token, received from a previous + ``ListRegionalInventories`` call. Provide the page token to + retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListRegionalInventories`` must match the call that + provided the page token. The token returned as + [nextPageToken][google.shopping.merchant.inventories.v1.ListRegionalInventoriesResponse.next_page_token] + in the response to the previous request. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListRegionalInventoriesResponse(proto.Message): + r"""Response message for the ``ListRegionalInventories`` method. + + Attributes: + regional_inventories (MutableSequence[google.shopping.merchant_inventories_v1.types.RegionalInventory]): + The ``RegionalInventory`` resources for the given product + from the specified account. + next_page_token (str): + A token, which can be sent as ``pageToken`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + regional_inventories: MutableSequence['RegionalInventory'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='RegionalInventory', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class InsertRegionalInventoryRequest(proto.Message): + r"""Request message for the ``InsertRegionalInventory`` method. + + Attributes: + parent (str): + Required. The account and product where this inventory will + be inserted. Format: + ``accounts/{account}/products/{product}`` + regional_inventory (google.shopping.merchant_inventories_v1.types.RegionalInventory): + Required. Regional inventory information to add to the + product. If the product already has a ``RegionalInventory`` + resource for the same ``region``, full replacement of the + ``RegionalInventory`` resource is performed. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + regional_inventory: 'RegionalInventory' = proto.Field( + proto.MESSAGE, + number=2, + message='RegionalInventory', + ) + + +class DeleteRegionalInventoryRequest(proto.Message): + r"""Request message for the ``DeleteRegionalInventory`` method. + + Attributes: + name (str): + Required. The name of the ``RegionalInventory`` resource to + delete. Format: + ``accounts/{account}/products/{product}/regionalInventories/{region}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/mypy.ini b/owl-bot-staging/google-shopping-merchant-inventories/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/noxfile.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/noxfile.py new file mode 100644 index 000000000000..084984b159e7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/noxfile.py @@ -0,0 +1,591 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import re +import shutil + +from typing import Dict, List +import warnings + +import nox + +BLACK_VERSION = "black[jupyter]==23.7.0" +ISORT_VERSION = "isort==5.11.0" + +LINT_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] + +DEFAULT_PYTHON_VERSION = ALL_PYTHON[-1] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = "google-shopping-merchant-inventories" + +UNIT_TEST_STANDARD_DEPENDENCIES = [ + "mock", + "asyncmock", + "pytest", + "pytest-cov", + "pytest-asyncio", +] +UNIT_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] +UNIT_TEST_LOCAL_DEPENDENCIES: List[str] = [] +UNIT_TEST_DEPENDENCIES: List[str] = [] +UNIT_TEST_EXTRAS: List[str] = [] +UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} + +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] +SYSTEM_TEST_STANDARD_DEPENDENCIES = [ + "mock", + "pytest", + "google-cloud-testutils", +] +SYSTEM_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_LOCAL_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_EXTRAS: List[str] = [] +SYSTEM_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} + +nox.options.sessions = [ + "unit", + "system", + "cover", + "lint", + "lint_setup_py", + "blacken", + "docs", +] + +# Error if a python version is missing +nox.options.error_on_missing_interpreters = True + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + "mypy", + "types-requests", + "types-protobuf", + ) + session.install(".") + session.run( + "mypy", + "-p", + "google", + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install("google-cloud-testutils") + session.install(".") + + session.run( + "lower-bound-checker", + "update", + "--package-name", + PACKAGE_NAME, + "--constraints-file", + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install("google-cloud-testutils") + session.install(".") + + session.run( + "lower-bound-checker", + "check", + "--package-name", + PACKAGE_NAME, + "--constraints-file", + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *LINT_PATHS, + ) + + session.run("flake8", "google", "tests") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *LINT_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def format(session): + """ + Run isort to sort imports. Then run black + to format code to uniform standard. + """ + session.install(BLACK_VERSION, ISORT_VERSION) + # Use the --fss option to sort imports using strict alphabetical order. + # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections + session.run( + "isort", + "--fss", + *LINT_PATHS, + ) + session.run( + "black", + *LINT_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("setuptools", "docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") + + +def install_unittest_dependencies(session, *constraints): + standard_deps = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_DEPENDENCIES + session.install(*standard_deps, *constraints) + + if UNIT_TEST_EXTERNAL_DEPENDENCIES: + warnings.warn( + "'unit_test_external_dependencies' is deprecated. Instead, please " + "use 'unit_test_dependencies' or 'unit_test_local_dependencies'.", + DeprecationWarning, + ) + session.install(*UNIT_TEST_EXTERNAL_DEPENDENCIES, *constraints) + + if UNIT_TEST_LOCAL_DEPENDENCIES: + session.install(*UNIT_TEST_LOCAL_DEPENDENCIES, *constraints) + + if UNIT_TEST_EXTRAS_BY_PYTHON: + extras = UNIT_TEST_EXTRAS_BY_PYTHON.get(session.python, []) + elif UNIT_TEST_EXTRAS: + extras = UNIT_TEST_EXTRAS + else: + extras = [] + + if extras: + session.install("-e", f".[{','.join(extras)}]", *constraints) + else: + session.install("-e", ".", *constraints) + + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + ["python", "upb", "cpp"], +) +def unit(session, protobuf_implementation): + # Install all test dependencies, then install this package in-place. + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): + session.skip("cpp implementation is not supported in python 3.11+") + + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) + install_unittest_dependencies(session, "-c", constraints_path) + + # TODO(https://github.com/googleapis/synthtool/issues/1976): + # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. + # The 'cpp' implementation requires Protobuf<4. + if protobuf_implementation == "cpp": + session.install("protobuf<4") + + # Run py.test against the unit tests. + session.run( + "py.test", + "--quiet", + f"--junitxml=unit_{session.python}_sponge_log.xml", + "--cov=google", + "--cov=tests/unit", + "--cov-append", + "--cov-config=.coveragerc", + "--cov-report=", + "--cov-fail-under=0", + os.path.join("tests", "unit"), + *session.posargs, + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +def install_systemtest_dependencies(session, *constraints): + session.install("--pre", "grpcio") + + session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_EXTERNAL_DEPENDENCIES: + session.install(*SYSTEM_TEST_EXTERNAL_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_LOCAL_DEPENDENCIES: + session.install("-e", *SYSTEM_TEST_LOCAL_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_DEPENDENCIES: + session.install("-e", *SYSTEM_TEST_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_EXTRAS_BY_PYTHON: + extras = SYSTEM_TEST_EXTRAS_BY_PYTHON.get(session.python, []) + elif SYSTEM_TEST_EXTRAS: + extras = SYSTEM_TEST_EXTRAS + else: + extras = [] + + if extras: + session.install("-e", f".[{','.join(extras)}]", *constraints) + else: + session.install("-e", ".", *constraints) + + +@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) +def system(session): + """Run the system test suite.""" + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) + system_test_path = os.path.join("tests", "system.py") + system_test_folder_path = os.path.join("tests", "system") + + # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. + if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": + session.skip("RUN_SYSTEM_TESTS is set to false, skipping") + # Install pyopenssl for mTLS testing. + if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": + session.install("pyopenssl") + + system_test_exists = os.path.exists(system_test_path) + system_test_folder_exists = os.path.exists(system_test_folder_path) + # Sanity check: only run tests if found. + if not system_test_exists and not system_test_folder_exists: + session.skip("System tests were not found") + + install_systemtest_dependencies(session, "-c", constraints_path) + + # Run py.test against the system tests. + if system_test_exists: + session.run( + "py.test", + "--quiet", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_path, + *session.posargs, + ) + if system_test_folder_exists: + session.run( + "py.test", + "--quiet", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_folder_path, + *session.posargs, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python="3.10") +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install( + # We need to pin to specific versions of the `sphinxcontrib-*` packages + # which still support sphinx 4.x. + # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 + # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. + "sphinxcontrib-applehelp==1.0.4", + "sphinxcontrib-devhelp==1.0.2", + "sphinxcontrib-htmlhelp==2.0.1", + "sphinxcontrib-qthelp==1.0.3", + "sphinxcontrib-serializinghtml==1.1.5", + "sphinx==4.5.0", + "alabaster", + "recommonmark", + ) + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python="3.10") +def docfx(session): + """Build the docfx yaml files for this library.""" + + session.install("-e", ".") + session.install( + # We need to pin to specific versions of the `sphinxcontrib-*` packages + # which still support sphinx 4.x. + # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 + # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. + "sphinxcontrib-applehelp==1.0.4", + "sphinxcontrib-devhelp==1.0.2", + "sphinxcontrib-htmlhelp==2.0.1", + "sphinxcontrib-qthelp==1.0.3", + "sphinxcontrib-serializinghtml==1.1.5", + "gcp-sphinx-docfx-yaml", + "alabaster", + "recommonmark", + ) + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-T", # show full traceback on exception + "-N", # no colors + "-D", + ( + "extensions=sphinx.ext.autodoc," + "sphinx.ext.autosummary," + "docfx_yaml.extension," + "sphinx.ext.intersphinx," + "sphinx.ext.coverage," + "sphinx.ext.napoleon," + "sphinx.ext.todo," + "sphinx.ext.viewcode," + "recommonmark" + ), + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +@nox.parametrize( + "protobuf_implementation", + ["python", "upb", "cpp"], +) +def prerelease_deps(session, protobuf_implementation): + """ + Run all tests with pre-release versions of dependencies installed + rather than the standard non pre-release versions. + Pre-release versions can be installed using + `pip install --pre `. + """ + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): + session.skip("cpp implementation is not supported in python 3.11+") + + # Install all dependencies + session.install("-e", ".") + + # Install dependencies for the unit test environment + unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES + session.install(*unit_deps_all) + + # Install dependencies for the system test environment + system_deps_all = ( + SYSTEM_TEST_STANDARD_DEPENDENCIES + + SYSTEM_TEST_EXTERNAL_DEPENDENCIES + + SYSTEM_TEST_EXTRAS + ) + session.install(*system_deps_all) + + # Because we test minimum dependency versions on the minimum Python + # version, the first version we test with in the unit tests sessions has a + # constraints file containing all dependencies and extras. + with open( + CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + # Install dependencies specified in `testing/constraints-X.txt`. + session.install(*constraints_deps) + + # Note: If a dependency is added to the `prerel_deps` list, + # the `core_dependencies_from_source` list in the `core_deps_from_source` + # nox session should also be updated. + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + "grpc-google-iam-v1", + "grpcio", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--ignore-installed", dep) + # TODO(https://github.com/grpc/grpc/issues/38965): Add `grpcio-status`` + # to the dictionary below once this bug is fixed. + # TODO(https://github.com/googleapis/google-cloud-python/issues/13643): Add + # `googleapis-common-protos` and `grpc-google-iam-v1` to the dictionary below + # once this bug is fixed. + package_namespaces = { + "google-api-core": "google.api_core", + "google-auth": "google.auth", + "grpcio": "grpc", + "protobuf": "google.protobuf", + "proto-plus": "proto", + } + + version_namespace = package_namespaces.get(dep) + + print(f"Installed {dep}") + if version_namespace: + session.run( + "python", + "-c", + f"import {version_namespace}; print({version_namespace}.__version__)", + ) + + session.run( + "py.test", + "tests/unit", + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +@nox.parametrize( + "protobuf_implementation", + ["python", "upb"], +) +def core_deps_from_source(session, protobuf_implementation): + """Run all tests with core dependencies installed from source + rather than pulling the dependencies from PyPI. + """ + + # Install all dependencies + session.install("-e", ".") + + # Install dependencies for the unit test environment + unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES + session.install(*unit_deps_all) + + # Install dependencies for the system test environment + system_deps_all = ( + SYSTEM_TEST_STANDARD_DEPENDENCIES + + SYSTEM_TEST_EXTERNAL_DEPENDENCIES + + SYSTEM_TEST_EXTRAS + ) + session.install(*system_deps_all) + + # Because we test minimum dependency versions on the minimum Python + # version, the first version we test with in the unit tests sessions has a + # constraints file containing all dependencies and extras. + with open( + CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + # Install dependencies specified in `testing/constraints-X.txt`. + session.install(*constraints_deps) + + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and + # `grpcio-status` should be added to the list below so that they are installed from source, + # rather than PyPI. + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2357): `protobuf` should be + # added to the list below so that it is installed from source, rather than PyPI + # Note: If a dependency is added to the `core_dependencies_from_source` list, + # the `prerel_deps` list in the `prerelease_deps` nox session should also be updated. + core_dependencies_from_source = [ + "googleapis-common-protos @ git+https://github.com/googleapis/google-cloud-python#egg=googleapis-common-protos&subdirectory=packages/googleapis-common-protos", + "google-api-core @ git+https://github.com/googleapis/python-api-core.git", + "google-auth @ git+https://github.com/googleapis/google-auth-library-python.git", + "grpc-google-iam-v1 @ git+https://github.com/googleapis/google-cloud-python#egg=grpc-google-iam-v1&subdirectory=packages/grpc-google-iam-v1", + "proto-plus @ git+https://github.com/googleapis/proto-plus-python.git", + ] + + for dep in core_dependencies_from_source: + session.install(dep, "--no-deps", "--ignore-installed") + print(f"Installed {dep}") + + session.run( + "py.test", + "tests/unit", + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_delete_local_inventory_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_delete_local_inventory_async.py new file mode 100644 index 000000000000..4447bc7f7759 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_delete_local_inventory_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteLocalInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1_generated_LocalInventoryService_DeleteLocalInventory_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1 + + +async def sample_delete_local_inventory(): + # Create a client + client = merchant_inventories_v1.LocalInventoryServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_inventories_v1.DeleteLocalInventoryRequest( + name="name_value", + ) + + # Make the request + await client.delete_local_inventory(request=request) + + +# [END merchantapi_v1_generated_LocalInventoryService_DeleteLocalInventory_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_delete_local_inventory_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_delete_local_inventory_sync.py new file mode 100644 index 000000000000..e7853c9faf39 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_delete_local_inventory_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteLocalInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1_generated_LocalInventoryService_DeleteLocalInventory_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1 + + +def sample_delete_local_inventory(): + # Create a client + client = merchant_inventories_v1.LocalInventoryServiceClient() + + # Initialize request argument(s) + request = merchant_inventories_v1.DeleteLocalInventoryRequest( + name="name_value", + ) + + # Make the request + client.delete_local_inventory(request=request) + + +# [END merchantapi_v1_generated_LocalInventoryService_DeleteLocalInventory_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_insert_local_inventory_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_insert_local_inventory_async.py new file mode 100644 index 000000000000..0e92a7d86fcd --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_insert_local_inventory_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InsertLocalInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1_generated_LocalInventoryService_InsertLocalInventory_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1 + + +async def sample_insert_local_inventory(): + # Create a client + client = merchant_inventories_v1.LocalInventoryServiceAsyncClient() + + # Initialize request argument(s) + local_inventory = merchant_inventories_v1.LocalInventory() + local_inventory.store_code = "store_code_value" + + request = merchant_inventories_v1.InsertLocalInventoryRequest( + parent="parent_value", + local_inventory=local_inventory, + ) + + # Make the request + response = await client.insert_local_inventory(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_LocalInventoryService_InsertLocalInventory_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_insert_local_inventory_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_insert_local_inventory_sync.py new file mode 100644 index 000000000000..aa46cd32e618 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_insert_local_inventory_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InsertLocalInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1_generated_LocalInventoryService_InsertLocalInventory_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1 + + +def sample_insert_local_inventory(): + # Create a client + client = merchant_inventories_v1.LocalInventoryServiceClient() + + # Initialize request argument(s) + local_inventory = merchant_inventories_v1.LocalInventory() + local_inventory.store_code = "store_code_value" + + request = merchant_inventories_v1.InsertLocalInventoryRequest( + parent="parent_value", + local_inventory=local_inventory, + ) + + # Make the request + response = client.insert_local_inventory(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_LocalInventoryService_InsertLocalInventory_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_list_local_inventories_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_list_local_inventories_async.py new file mode 100644 index 000000000000..ee786a305932 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_list_local_inventories_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1_generated_LocalInventoryService_ListLocalInventories_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1 + + +async def sample_list_local_inventories(): + # Create a client + client = merchant_inventories_v1.LocalInventoryServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_inventories_v1.ListLocalInventoriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_local_inventories(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1_generated_LocalInventoryService_ListLocalInventories_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_list_local_inventories_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_list_local_inventories_sync.py new file mode 100644 index 000000000000..589cd807edd9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_list_local_inventories_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1_generated_LocalInventoryService_ListLocalInventories_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1 + + +def sample_list_local_inventories(): + # Create a client + client = merchant_inventories_v1.LocalInventoryServiceClient() + + # Initialize request argument(s) + request = merchant_inventories_v1.ListLocalInventoriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_local_inventories(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1_generated_LocalInventoryService_ListLocalInventories_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_delete_regional_inventory_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_delete_regional_inventory_async.py new file mode 100644 index 000000000000..32cdc596e48a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_delete_regional_inventory_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteRegionalInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1_generated_RegionalInventoryService_DeleteRegionalInventory_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1 + + +async def sample_delete_regional_inventory(): + # Create a client + client = merchant_inventories_v1.RegionalInventoryServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_inventories_v1.DeleteRegionalInventoryRequest( + name="name_value", + ) + + # Make the request + await client.delete_regional_inventory(request=request) + + +# [END merchantapi_v1_generated_RegionalInventoryService_DeleteRegionalInventory_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_delete_regional_inventory_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_delete_regional_inventory_sync.py new file mode 100644 index 000000000000..7b8ec6059d40 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_delete_regional_inventory_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteRegionalInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1_generated_RegionalInventoryService_DeleteRegionalInventory_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1 + + +def sample_delete_regional_inventory(): + # Create a client + client = merchant_inventories_v1.RegionalInventoryServiceClient() + + # Initialize request argument(s) + request = merchant_inventories_v1.DeleteRegionalInventoryRequest( + name="name_value", + ) + + # Make the request + client.delete_regional_inventory(request=request) + + +# [END merchantapi_v1_generated_RegionalInventoryService_DeleteRegionalInventory_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_insert_regional_inventory_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_insert_regional_inventory_async.py new file mode 100644 index 000000000000..8e2e6166147a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_insert_regional_inventory_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InsertRegionalInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1_generated_RegionalInventoryService_InsertRegionalInventory_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1 + + +async def sample_insert_regional_inventory(): + # Create a client + client = merchant_inventories_v1.RegionalInventoryServiceAsyncClient() + + # Initialize request argument(s) + regional_inventory = merchant_inventories_v1.RegionalInventory() + regional_inventory.region = "region_value" + + request = merchant_inventories_v1.InsertRegionalInventoryRequest( + parent="parent_value", + regional_inventory=regional_inventory, + ) + + # Make the request + response = await client.insert_regional_inventory(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_RegionalInventoryService_InsertRegionalInventory_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_insert_regional_inventory_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_insert_regional_inventory_sync.py new file mode 100644 index 000000000000..b9e3adf5ee22 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_insert_regional_inventory_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InsertRegionalInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1_generated_RegionalInventoryService_InsertRegionalInventory_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1 + + +def sample_insert_regional_inventory(): + # Create a client + client = merchant_inventories_v1.RegionalInventoryServiceClient() + + # Initialize request argument(s) + regional_inventory = merchant_inventories_v1.RegionalInventory() + regional_inventory.region = "region_value" + + request = merchant_inventories_v1.InsertRegionalInventoryRequest( + parent="parent_value", + regional_inventory=regional_inventory, + ) + + # Make the request + response = client.insert_regional_inventory(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_RegionalInventoryService_InsertRegionalInventory_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_list_regional_inventories_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_list_regional_inventories_async.py new file mode 100644 index 000000000000..5aad14664768 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_list_regional_inventories_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListRegionalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1_generated_RegionalInventoryService_ListRegionalInventories_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1 + + +async def sample_list_regional_inventories(): + # Create a client + client = merchant_inventories_v1.RegionalInventoryServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_inventories_v1.ListRegionalInventoriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_regional_inventories(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1_generated_RegionalInventoryService_ListRegionalInventories_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_list_regional_inventories_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_list_regional_inventories_sync.py new file mode 100644 index 000000000000..30028dd32ca7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_list_regional_inventories_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListRegionalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1_generated_RegionalInventoryService_ListRegionalInventories_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1 + + +def sample_list_regional_inventories(): + # Create a client + client = merchant_inventories_v1.RegionalInventoryServiceClient() + + # Initialize request argument(s) + request = merchant_inventories_v1.ListRegionalInventoriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_regional_inventories(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1_generated_RegionalInventoryService_ListRegionalInventories_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1.json b/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1.json new file mode 100644 index 000000000000..543cf842885a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1.json @@ -0,0 +1,953 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.shopping.merchant.inventories.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-shopping-merchant-inventories", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_inventories_v1.LocalInventoryServiceAsyncClient", + "shortName": "LocalInventoryServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_inventories_v1.LocalInventoryServiceAsyncClient.delete_local_inventory", + "method": { + "fullName": "google.shopping.merchant.inventories.v1.LocalInventoryService.DeleteLocalInventory", + "service": { + "fullName": "google.shopping.merchant.inventories.v1.LocalInventoryService", + "shortName": "LocalInventoryService" + }, + "shortName": "DeleteLocalInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1.types.DeleteLocalInventoryRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_local_inventory" + }, + "description": "Sample for DeleteLocalInventory", + "file": "merchantapi_v1_generated_local_inventory_service_delete_local_inventory_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_LocalInventoryService_DeleteLocalInventory_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_local_inventory_service_delete_local_inventory_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_inventories_v1.LocalInventoryServiceClient", + "shortName": "LocalInventoryServiceClient" + }, + "fullName": "google.shopping.merchant_inventories_v1.LocalInventoryServiceClient.delete_local_inventory", + "method": { + "fullName": "google.shopping.merchant.inventories.v1.LocalInventoryService.DeleteLocalInventory", + "service": { + "fullName": "google.shopping.merchant.inventories.v1.LocalInventoryService", + "shortName": "LocalInventoryService" + }, + "shortName": "DeleteLocalInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1.types.DeleteLocalInventoryRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_local_inventory" + }, + "description": "Sample for DeleteLocalInventory", + "file": "merchantapi_v1_generated_local_inventory_service_delete_local_inventory_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_LocalInventoryService_DeleteLocalInventory_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_local_inventory_service_delete_local_inventory_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_inventories_v1.LocalInventoryServiceAsyncClient", + "shortName": "LocalInventoryServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_inventories_v1.LocalInventoryServiceAsyncClient.insert_local_inventory", + "method": { + "fullName": "google.shopping.merchant.inventories.v1.LocalInventoryService.InsertLocalInventory", + "service": { + "fullName": "google.shopping.merchant.inventories.v1.LocalInventoryService", + "shortName": "LocalInventoryService" + }, + "shortName": "InsertLocalInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1.types.InsertLocalInventoryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_inventories_v1.types.LocalInventory", + "shortName": "insert_local_inventory" + }, + "description": "Sample for InsertLocalInventory", + "file": "merchantapi_v1_generated_local_inventory_service_insert_local_inventory_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_LocalInventoryService_InsertLocalInventory_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_local_inventory_service_insert_local_inventory_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_inventories_v1.LocalInventoryServiceClient", + "shortName": "LocalInventoryServiceClient" + }, + "fullName": "google.shopping.merchant_inventories_v1.LocalInventoryServiceClient.insert_local_inventory", + "method": { + "fullName": "google.shopping.merchant.inventories.v1.LocalInventoryService.InsertLocalInventory", + "service": { + "fullName": "google.shopping.merchant.inventories.v1.LocalInventoryService", + "shortName": "LocalInventoryService" + }, + "shortName": "InsertLocalInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1.types.InsertLocalInventoryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_inventories_v1.types.LocalInventory", + "shortName": "insert_local_inventory" + }, + "description": "Sample for InsertLocalInventory", + "file": "merchantapi_v1_generated_local_inventory_service_insert_local_inventory_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_LocalInventoryService_InsertLocalInventory_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_local_inventory_service_insert_local_inventory_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_inventories_v1.LocalInventoryServiceAsyncClient", + "shortName": "LocalInventoryServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_inventories_v1.LocalInventoryServiceAsyncClient.list_local_inventories", + "method": { + "fullName": "google.shopping.merchant.inventories.v1.LocalInventoryService.ListLocalInventories", + "service": { + "fullName": "google.shopping.merchant.inventories.v1.LocalInventoryService", + "shortName": "LocalInventoryService" + }, + "shortName": "ListLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1.types.ListLocalInventoriesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_inventories_v1.services.local_inventory_service.pagers.ListLocalInventoriesAsyncPager", + "shortName": "list_local_inventories" + }, + "description": "Sample for ListLocalInventories", + "file": "merchantapi_v1_generated_local_inventory_service_list_local_inventories_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_LocalInventoryService_ListLocalInventories_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_local_inventory_service_list_local_inventories_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_inventories_v1.LocalInventoryServiceClient", + "shortName": "LocalInventoryServiceClient" + }, + "fullName": "google.shopping.merchant_inventories_v1.LocalInventoryServiceClient.list_local_inventories", + "method": { + "fullName": "google.shopping.merchant.inventories.v1.LocalInventoryService.ListLocalInventories", + "service": { + "fullName": "google.shopping.merchant.inventories.v1.LocalInventoryService", + "shortName": "LocalInventoryService" + }, + "shortName": "ListLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1.types.ListLocalInventoriesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_inventories_v1.services.local_inventory_service.pagers.ListLocalInventoriesPager", + "shortName": "list_local_inventories" + }, + "description": "Sample for ListLocalInventories", + "file": "merchantapi_v1_generated_local_inventory_service_list_local_inventories_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_LocalInventoryService_ListLocalInventories_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_local_inventory_service_list_local_inventories_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_inventories_v1.RegionalInventoryServiceAsyncClient", + "shortName": "RegionalInventoryServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_inventories_v1.RegionalInventoryServiceAsyncClient.delete_regional_inventory", + "method": { + "fullName": "google.shopping.merchant.inventories.v1.RegionalInventoryService.DeleteRegionalInventory", + "service": { + "fullName": "google.shopping.merchant.inventories.v1.RegionalInventoryService", + "shortName": "RegionalInventoryService" + }, + "shortName": "DeleteRegionalInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1.types.DeleteRegionalInventoryRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_regional_inventory" + }, + "description": "Sample for DeleteRegionalInventory", + "file": "merchantapi_v1_generated_regional_inventory_service_delete_regional_inventory_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_RegionalInventoryService_DeleteRegionalInventory_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_regional_inventory_service_delete_regional_inventory_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_inventories_v1.RegionalInventoryServiceClient", + "shortName": "RegionalInventoryServiceClient" + }, + "fullName": "google.shopping.merchant_inventories_v1.RegionalInventoryServiceClient.delete_regional_inventory", + "method": { + "fullName": "google.shopping.merchant.inventories.v1.RegionalInventoryService.DeleteRegionalInventory", + "service": { + "fullName": "google.shopping.merchant.inventories.v1.RegionalInventoryService", + "shortName": "RegionalInventoryService" + }, + "shortName": "DeleteRegionalInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1.types.DeleteRegionalInventoryRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_regional_inventory" + }, + "description": "Sample for DeleteRegionalInventory", + "file": "merchantapi_v1_generated_regional_inventory_service_delete_regional_inventory_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_RegionalInventoryService_DeleteRegionalInventory_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_regional_inventory_service_delete_regional_inventory_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_inventories_v1.RegionalInventoryServiceAsyncClient", + "shortName": "RegionalInventoryServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_inventories_v1.RegionalInventoryServiceAsyncClient.insert_regional_inventory", + "method": { + "fullName": "google.shopping.merchant.inventories.v1.RegionalInventoryService.InsertRegionalInventory", + "service": { + "fullName": "google.shopping.merchant.inventories.v1.RegionalInventoryService", + "shortName": "RegionalInventoryService" + }, + "shortName": "InsertRegionalInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1.types.InsertRegionalInventoryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_inventories_v1.types.RegionalInventory", + "shortName": "insert_regional_inventory" + }, + "description": "Sample for InsertRegionalInventory", + "file": "merchantapi_v1_generated_regional_inventory_service_insert_regional_inventory_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_RegionalInventoryService_InsertRegionalInventory_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_regional_inventory_service_insert_regional_inventory_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_inventories_v1.RegionalInventoryServiceClient", + "shortName": "RegionalInventoryServiceClient" + }, + "fullName": "google.shopping.merchant_inventories_v1.RegionalInventoryServiceClient.insert_regional_inventory", + "method": { + "fullName": "google.shopping.merchant.inventories.v1.RegionalInventoryService.InsertRegionalInventory", + "service": { + "fullName": "google.shopping.merchant.inventories.v1.RegionalInventoryService", + "shortName": "RegionalInventoryService" + }, + "shortName": "InsertRegionalInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1.types.InsertRegionalInventoryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_inventories_v1.types.RegionalInventory", + "shortName": "insert_regional_inventory" + }, + "description": "Sample for InsertRegionalInventory", + "file": "merchantapi_v1_generated_regional_inventory_service_insert_regional_inventory_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_RegionalInventoryService_InsertRegionalInventory_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_regional_inventory_service_insert_regional_inventory_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_inventories_v1.RegionalInventoryServiceAsyncClient", + "shortName": "RegionalInventoryServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_inventories_v1.RegionalInventoryServiceAsyncClient.list_regional_inventories", + "method": { + "fullName": "google.shopping.merchant.inventories.v1.RegionalInventoryService.ListRegionalInventories", + "service": { + "fullName": "google.shopping.merchant.inventories.v1.RegionalInventoryService", + "shortName": "RegionalInventoryService" + }, + "shortName": "ListRegionalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1.types.ListRegionalInventoriesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_inventories_v1.services.regional_inventory_service.pagers.ListRegionalInventoriesAsyncPager", + "shortName": "list_regional_inventories" + }, + "description": "Sample for ListRegionalInventories", + "file": "merchantapi_v1_generated_regional_inventory_service_list_regional_inventories_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_RegionalInventoryService_ListRegionalInventories_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_regional_inventory_service_list_regional_inventories_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_inventories_v1.RegionalInventoryServiceClient", + "shortName": "RegionalInventoryServiceClient" + }, + "fullName": "google.shopping.merchant_inventories_v1.RegionalInventoryServiceClient.list_regional_inventories", + "method": { + "fullName": "google.shopping.merchant.inventories.v1.RegionalInventoryService.ListRegionalInventories", + "service": { + "fullName": "google.shopping.merchant.inventories.v1.RegionalInventoryService", + "shortName": "RegionalInventoryService" + }, + "shortName": "ListRegionalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1.types.ListRegionalInventoriesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_inventories_v1.services.regional_inventory_service.pagers.ListRegionalInventoriesPager", + "shortName": "list_regional_inventories" + }, + "description": "Sample for ListRegionalInventories", + "file": "merchantapi_v1_generated_regional_inventory_service_list_regional_inventories_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_RegionalInventoryService_ListRegionalInventories_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_regional_inventory_service_list_regional_inventories_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/scripts/fixup_merchant_inventories_v1_keywords.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/scripts/fixup_merchant_inventories_v1_keywords.py new file mode 100644 index 000000000000..02d464643567 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/scripts/fixup_merchant_inventories_v1_keywords.py @@ -0,0 +1,181 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class merchant_inventoriesCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'delete_local_inventory': ('name', ), + 'delete_regional_inventory': ('name', ), + 'insert_local_inventory': ('parent', 'local_inventory', ), + 'insert_regional_inventory': ('parent', 'regional_inventory', ), + 'list_local_inventories': ('parent', 'page_size', 'page_token', ), + 'list_regional_inventories': ('parent', 'page_size', 'page_token', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=merchant_inventoriesCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the merchant_inventories client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/setup.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/setup.py new file mode 100644 index 000000000000..4fd17ebb95a5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/setup.py @@ -0,0 +1,99 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import re + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-shopping-merchant-inventories' + + +description = "Google Shopping Merchant Inventories API client library" + +version = None + +with open(os.path.join(package_root, 'google/shopping/merchant_inventories/gapic_version.py')) as fp: + version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) + assert (len(version_candidates) == 1) + version = version_candidates[0] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.1, <3.0.0,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0", + "proto-plus >= 1.25.0, <2.0.0; python_version >= '3.13'", + "protobuf>=3.20.2,<7.0.0,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", + "google-shopping-type >= 0.1.6, <1.0.0", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-inventories" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.find_namespace_packages() + if package.startswith("google") +] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + extras_require=extras, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.10.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.11.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.12.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.13.txt new file mode 100644 index 000000000000..0112695e5bbb --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.13.txt @@ -0,0 +1,12 @@ +# We use the constraints file for the latest Python version +# (currently this file) to check that the latest +# major versions of dependencies are supported in setup.py. +# List all library dependencies and extras in this file. +# Require the latest major version be installed for each dependency. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# Then this file should have google-cloud-foo>=1 +google-api-core>=2 +google-auth>=2 +proto-plus>=1 +protobuf>=6 +google-shopping-type>=0 diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..2af887ec8ba0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.7.txt @@ -0,0 +1,11 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.1 +google-auth==2.14.1 +proto-plus==1.22.3 +protobuf==3.20.2 +google-shopping-type==0.1.6 diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.8.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.9.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/merchant_inventories_v1/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/merchant_inventories_v1/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/merchant_inventories_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/merchant_inventories_v1/test_local_inventory_service.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/merchant_inventories_v1/test_local_inventory_service.py new file mode 100644 index 000000000000..a2a0b428a3f0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/merchant_inventories_v1/test_local_inventory_service.py @@ -0,0 +1,3632 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +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 proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +try: + from google.auth.aio import credentials as ga_credentials_async + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import 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 +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +from google.protobuf import timestamp_pb2 # type: ignore +from google.shopping.merchant_inventories_v1.services.local_inventory_service import LocalInventoryServiceAsyncClient +from google.shopping.merchant_inventories_v1.services.local_inventory_service import LocalInventoryServiceClient +from google.shopping.merchant_inventories_v1.services.local_inventory_service import pagers +from google.shopping.merchant_inventories_v1.services.local_inventory_service import transports +from google.shopping.merchant_inventories_v1.types import inventories_common +from google.shopping.merchant_inventories_v1.types import localinventory +from google.shopping.type.types import types +from google.type import interval_pb2 # type: ignore +import google.auth + + + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + +# 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 + +# 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 + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert LocalInventoryServiceClient._get_default_mtls_endpoint(None) is None + assert LocalInventoryServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert LocalInventoryServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert LocalInventoryServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert LocalInventoryServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert LocalInventoryServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert LocalInventoryServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert LocalInventoryServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert LocalInventoryServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + LocalInventoryServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert LocalInventoryServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert LocalInventoryServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert LocalInventoryServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + LocalInventoryServiceClient._read_environment_variables() + 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 LocalInventoryServiceClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert LocalInventoryServiceClient._get_client_cert_source(None, False) is None + assert LocalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert LocalInventoryServiceClient._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 LocalInventoryServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert LocalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(LocalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceClient)) +@mock.patch.object(LocalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = LocalInventoryServiceClient._DEFAULT_UNIVERSE + default_endpoint = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert LocalInventoryServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert LocalInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + assert LocalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert LocalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "always") == LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + assert LocalInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + assert LocalInventoryServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert LocalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + LocalInventoryServiceClient._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 LocalInventoryServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert LocalInventoryServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert LocalInventoryServiceClient._get_universe_domain(None, None) == LocalInventoryServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + LocalInventoryServiceClient._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) +]) +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) + client = LocalInventoryServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + +@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") + client = LocalInventoryServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + +@pytest.mark.parametrize("client_class,transport_name", [ + (LocalInventoryServiceClient, "grpc"), + (LocalInventoryServiceAsyncClient, "grpc_asyncio"), + (LocalInventoryServiceClient, "rest"), +]) +def test_local_inventory_service_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: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'merchantapi.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://merchantapi.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.LocalInventoryServiceGrpcTransport, "grpc"), + (transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.LocalInventoryServiceRestTransport, "rest"), +]) +def test_local_inventory_service_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: + 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", [ + (LocalInventoryServiceClient, "grpc"), + (LocalInventoryServiceAsyncClient, "grpc_asyncio"), + (LocalInventoryServiceClient, "rest"), +]) +def test_local_inventory_service_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: + factory.return_value = creds + 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) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'merchantapi.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://merchantapi.googleapis.com' + ) + + +def test_local_inventory_service_client_get_transport_class(): + transport = LocalInventoryServiceClient.get_transport_class() + available_transports = [ + transports.LocalInventoryServiceGrpcTransport, + transports.LocalInventoryServiceRestTransport, + ] + assert transport in available_transports + + transport = LocalInventoryServiceClient.get_transport_class("grpc") + assert transport == transports.LocalInventoryServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc"), + (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest"), +]) +@mock.patch.object(LocalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceClient)) +@mock.patch.object(LocalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceAsyncClient)) +def test_local_inventory_service_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(LocalInventoryServiceClient, '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(LocalInventoryServiceClient, '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: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + 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=None, + ) + + # 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: + 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), + 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=None, + ) + + # 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: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + 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=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) 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`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + 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: + 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), + 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", [ + (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc", "true"), + (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc", "false"), + (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest", "true"), + (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(LocalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceClient)) +@mock.patch.object(LocalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_local_inventory_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, 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) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # 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): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # 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): + 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), + 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=None, + ) + + +@pytest.mark.parametrize("client_class", [ + LocalInventoryServiceClient, LocalInventoryServiceAsyncClient +]) +@mock.patch.object(LocalInventoryServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LocalInventoryServiceClient)) +@mock.patch.object(LocalInventoryServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LocalInventoryServiceAsyncClient)) +def test_local_inventory_service_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) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + 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) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + 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 "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # 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): + 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() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) 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`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + LocalInventoryServiceClient, LocalInventoryServiceAsyncClient +]) +@mock.patch.object(LocalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceClient)) +@mock.patch.object(LocalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceAsyncClient)) +def test_local_inventory_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = LocalInventoryServiceClient._DEFAULT_UNIVERSE + default_endpoint = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = LocalInventoryServiceClient._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()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + 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()) + 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) + + # 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. + options = client_options.ClientOptions() + 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()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc"), + (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest"), +]) +def test_local_inventory_service_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: + 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), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc", grpc_helpers), + (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest", None), +]) +def test_local_inventory_service_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" + ) + + 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), + 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=None, + ) + +def test_local_inventory_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_inventories_v1.services.local_inventory_service.transports.LocalInventoryServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = LocalInventoryServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + 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=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc", grpc_helpers), + (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_local_inventory_service_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" + ) + + 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), + 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=None, + ) + + # 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: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "merchantapi.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/content', +), + scopes=None, + default_host="merchantapi.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + localinventory.ListLocalInventoriesRequest, + dict, +]) +def test_list_local_inventories(request_type, transport: str = 'grpc'): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = localinventory.ListLocalInventoriesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = localinventory.ListLocalInventoriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListLocalInventoriesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_local_inventories_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = localinventory.ListLocalInventoriesRequest( + 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_local_inventories), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_local_inventories(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == localinventory.ListLocalInventoriesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_local_inventories_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_local_inventories in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_local_inventories] = mock_rpc + request = {} + client.list_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_local_inventories(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_local_inventories_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_local_inventories 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_local_inventories] = mock_rpc + + request = {} + await client.list_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_local_inventories(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_local_inventories_async(transport: str = 'grpc_asyncio', request_type=localinventory.ListLocalInventoriesRequest): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(localinventory.ListLocalInventoriesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = localinventory.ListLocalInventoriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListLocalInventoriesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_local_inventories_async_from_dict(): + await test_list_local_inventories_async(request_type=dict) + +def test_list_local_inventories_field_headers(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = localinventory.ListLocalInventoriesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + call.return_value = localinventory.ListLocalInventoriesResponse() + client.list_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_local_inventories_field_headers_async(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = localinventory.ListLocalInventoriesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.ListLocalInventoriesResponse()) + await client.list_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_local_inventories_flattened(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = localinventory.ListLocalInventoriesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_local_inventories( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_local_inventories_flattened_error(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_local_inventories( + localinventory.ListLocalInventoriesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_local_inventories_flattened_async(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = localinventory.ListLocalInventoriesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.ListLocalInventoriesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_local_inventories( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_local_inventories_flattened_error_async(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_local_inventories( + localinventory.ListLocalInventoriesRequest(), + parent='parent_value', + ) + + +def test_list_local_inventories_pager(transport_name: str = "grpc"): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + next_page_token='abc', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[], + next_page_token='def', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + ], + next_page_token='ghi', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_local_inventories(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, localinventory.LocalInventory) + for i in results) +def test_list_local_inventories_pages(transport_name: str = "grpc"): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + next_page_token='abc', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[], + next_page_token='def', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + ], + next_page_token='ghi', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + ), + RuntimeError, + ) + pages = list(client.list_local_inventories(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_local_inventories_async_pager(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + next_page_token='abc', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[], + next_page_token='def', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + ], + next_page_token='ghi', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_local_inventories(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, localinventory.LocalInventory) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_local_inventories_async_pages(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + next_page_token='abc', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[], + next_page_token='def', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + ], + next_page_token='ghi', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_local_inventories(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + localinventory.InsertLocalInventoryRequest, + dict, +]) +def test_insert_local_inventory(request_type, transport: str = 'grpc'): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_local_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = localinventory.LocalInventory( + name='name_value', + account=749, + store_code='store_code_value', + ) + response = client.insert_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = localinventory.InsertLocalInventoryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, localinventory.LocalInventory) + assert response.name == 'name_value' + assert response.account == 749 + assert response.store_code == 'store_code_value' + + +def test_insert_local_inventory_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = localinventory.InsertLocalInventoryRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_local_inventory), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.insert_local_inventory(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == localinventory.InsertLocalInventoryRequest( + parent='parent_value', + ) + +def test_insert_local_inventory_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.insert_local_inventory in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.insert_local_inventory] = mock_rpc + request = {} + client.insert_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.insert_local_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_insert_local_inventory_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.insert_local_inventory 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.insert_local_inventory] = mock_rpc + + request = {} + await client.insert_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.insert_local_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_insert_local_inventory_async(transport: str = 'grpc_asyncio', request_type=localinventory.InsertLocalInventoryRequest): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_local_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(localinventory.LocalInventory( + name='name_value', + account=749, + store_code='store_code_value', + )) + response = await client.insert_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = localinventory.InsertLocalInventoryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, localinventory.LocalInventory) + assert response.name == 'name_value' + assert response.account == 749 + assert response.store_code == 'store_code_value' + + +@pytest.mark.asyncio +async def test_insert_local_inventory_async_from_dict(): + await test_insert_local_inventory_async(request_type=dict) + +def test_insert_local_inventory_field_headers(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = localinventory.InsertLocalInventoryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_local_inventory), + '__call__') as call: + call.return_value = localinventory.LocalInventory() + client.insert_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_insert_local_inventory_field_headers_async(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = localinventory.InsertLocalInventoryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_local_inventory), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.LocalInventory()) + await client.insert_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + localinventory.DeleteLocalInventoryRequest, + dict, +]) +def test_delete_local_inventory(request_type, transport: str = 'grpc'): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = localinventory.DeleteLocalInventoryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_local_inventory_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = localinventory.DeleteLocalInventoryRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_local_inventory(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == localinventory.DeleteLocalInventoryRequest( + name='name_value', + ) + +def test_delete_local_inventory_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_local_inventory in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_local_inventory] = mock_rpc + request = {} + client.delete_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_local_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_local_inventory_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_local_inventory 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_local_inventory] = mock_rpc + + request = {} + await client.delete_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_local_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_local_inventory_async(transport: str = 'grpc_asyncio', request_type=localinventory.DeleteLocalInventoryRequest): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = localinventory.DeleteLocalInventoryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_local_inventory_async_from_dict(): + await test_delete_local_inventory_async(request_type=dict) + +def test_delete_local_inventory_field_headers(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = localinventory.DeleteLocalInventoryRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__call__') as call: + call.return_value = None + client.delete_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_local_inventory_field_headers_async(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = localinventory.DeleteLocalInventoryRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_local_inventory_flattened(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__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_local_inventory( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_local_inventory_flattened_error(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_local_inventory( + localinventory.DeleteLocalInventoryRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_local_inventory_flattened_async(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_local_inventory( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_local_inventory_flattened_error_async(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_local_inventory( + localinventory.DeleteLocalInventoryRequest(), + name='name_value', + ) + + +def test_list_local_inventories_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_local_inventories in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_local_inventories] = mock_rpc + + request = {} + client.list_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_local_inventories(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_local_inventories_rest_required_fields(request_type=localinventory.ListLocalInventoriesRequest): + transport_class = transports.LocalInventoryServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_local_inventories._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_local_inventories._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", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = localinventory.ListLocalInventoriesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = localinventory.ListLocalInventoriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_local_inventories(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_local_inventories_rest_unset_required_fields(): + transport = transports.LocalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_local_inventories._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_local_inventories_rest_flattened(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = localinventory.ListLocalInventoriesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1/products/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = localinventory.ListLocalInventoriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_local_inventories(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/inventories/v1/{parent=accounts/*/products/*}/localInventories" % client.transport._host, args[1]) + + +def test_list_local_inventories_rest_flattened_error(transport: str = 'rest'): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_local_inventories( + localinventory.ListLocalInventoriesRequest(), + parent='parent_value', + ) + + +def test_list_local_inventories_rest_pager(transport: str = 'rest'): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + next_page_token='abc', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[], + next_page_token='def', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + ], + next_page_token='ghi', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(localinventory.ListLocalInventoriesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'accounts/sample1/products/sample2'} + + pager = client.list_local_inventories(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, localinventory.LocalInventory) + for i in results) + + pages = list(client.list_local_inventories(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_insert_local_inventory_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.insert_local_inventory in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.insert_local_inventory] = mock_rpc + + request = {} + client.insert_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.insert_local_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_insert_local_inventory_rest_required_fields(request_type=localinventory.InsertLocalInventoryRequest): + transport_class = transports.LocalInventoryServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).insert_local_inventory._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).insert_local_inventory._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = localinventory.LocalInventory() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = localinventory.LocalInventory.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.insert_local_inventory(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_insert_local_inventory_rest_unset_required_fields(): + transport = transports.LocalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.insert_local_inventory._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "localInventory", ))) + + +def test_delete_local_inventory_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_local_inventory in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_local_inventory] = mock_rpc + + request = {} + client.delete_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_local_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_local_inventory_rest_required_fields(request_type=localinventory.DeleteLocalInventoryRequest): + transport_class = transports.LocalInventoryServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_local_inventory._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_local_inventory._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_local_inventory(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_local_inventory_rest_unset_required_fields(): + transport = transports.LocalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_local_inventory._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_local_inventory_rest_flattened(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/products/sample2/localInventories/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_local_inventory(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/inventories/v1/{name=accounts/*/products/*/localInventories/*}" % client.transport._host, args[1]) + + +def test_delete_local_inventory_rest_flattened_error(transport: str = 'rest'): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_local_inventory( + localinventory.DeleteLocalInventoryRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.LocalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.LocalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LocalInventoryServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.LocalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = LocalInventoryServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = LocalInventoryServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.LocalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LocalInventoryServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.LocalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = LocalInventoryServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.LocalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.LocalInventoryServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.LocalInventoryServiceGrpcTransport, + transports.LocalInventoryServiceGrpcAsyncIOTransport, + transports.LocalInventoryServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_kind_grpc(): + transport = LocalInventoryServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_local_inventories_empty_call_grpc(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + call.return_value = localinventory.ListLocalInventoriesResponse() + client.list_local_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = localinventory.ListLocalInventoriesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_insert_local_inventory_empty_call_grpc(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_local_inventory), + '__call__') as call: + call.return_value = localinventory.LocalInventory() + client.insert_local_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = localinventory.InsertLocalInventoryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_local_inventory_empty_call_grpc(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__call__') as call: + call.return_value = None + client.delete_local_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = localinventory.DeleteLocalInventoryRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = LocalInventoryServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_local_inventories_empty_call_grpc_asyncio(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.ListLocalInventoriesResponse( + next_page_token='next_page_token_value', + )) + await client.list_local_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = localinventory.ListLocalInventoriesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_insert_local_inventory_empty_call_grpc_asyncio(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_local_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.LocalInventory( + name='name_value', + account=749, + store_code='store_code_value', + )) + await client.insert_local_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = localinventory.InsertLocalInventoryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_local_inventory_empty_call_grpc_asyncio(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_local_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = localinventory.DeleteLocalInventoryRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = LocalInventoryServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_local_inventories_rest_bad_request(request_type=localinventory.ListLocalInventoriesRequest): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/products/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_local_inventories(request) + + +@pytest.mark.parametrize("request_type", [ + localinventory.ListLocalInventoriesRequest, + dict, +]) +def test_list_local_inventories_rest_call_success(request_type): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/products/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = localinventory.ListLocalInventoriesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = localinventory.ListLocalInventoriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_local_inventories(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListLocalInventoriesPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_local_inventories_rest_interceptors(null_interceptor): + transport = transports.LocalInventoryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LocalInventoryServiceRestInterceptor(), + ) + client = LocalInventoryServiceClient(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.LocalInventoryServiceRestInterceptor, "post_list_local_inventories") as post, \ + mock.patch.object(transports.LocalInventoryServiceRestInterceptor, "post_list_local_inventories_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.LocalInventoryServiceRestInterceptor, "pre_list_local_inventories") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = localinventory.ListLocalInventoriesRequest.pb(localinventory.ListLocalInventoriesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = localinventory.ListLocalInventoriesResponse.to_json(localinventory.ListLocalInventoriesResponse()) + req.return_value.content = return_value + + request = localinventory.ListLocalInventoriesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = localinventory.ListLocalInventoriesResponse() + post_with_metadata.return_value = localinventory.ListLocalInventoriesResponse(), metadata + + client.list_local_inventories(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_insert_local_inventory_rest_bad_request(request_type=localinventory.InsertLocalInventoryRequest): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/products/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.insert_local_inventory(request) + + +@pytest.mark.parametrize("request_type", [ + localinventory.InsertLocalInventoryRequest, + dict, +]) +def test_insert_local_inventory_rest_call_success(request_type): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/products/sample2'} + request_init["local_inventory"] = {'name': 'name_value', 'account': 749, 'store_code': 'store_code_value', 'local_inventory_attributes': {'price': {'amount_micros': 1408, 'currency_code': 'currency_code_value'}, 'sale_price': {}, 'sale_price_effective_date': {'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}}, 'availability': 1, 'quantity': 895, 'pickup_method': 1, 'pickup_sla': 1, 'instore_product_location': 'instore_product_location_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 + + # Determine if the message type is proto-plus or protobuf + test_field = localinventory.InsertLocalInventoryRequest.meta.fields["local_inventory"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["local_inventory"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["local_inventory"][field])): + del request_init["local_inventory"][field][i][subfield] + else: + del request_init["local_inventory"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = localinventory.LocalInventory( + name='name_value', + account=749, + store_code='store_code_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = localinventory.LocalInventory.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.insert_local_inventory(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, localinventory.LocalInventory) + assert response.name == 'name_value' + assert response.account == 749 + assert response.store_code == 'store_code_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_insert_local_inventory_rest_interceptors(null_interceptor): + transport = transports.LocalInventoryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LocalInventoryServiceRestInterceptor(), + ) + client = LocalInventoryServiceClient(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.LocalInventoryServiceRestInterceptor, "post_insert_local_inventory") as post, \ + mock.patch.object(transports.LocalInventoryServiceRestInterceptor, "post_insert_local_inventory_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.LocalInventoryServiceRestInterceptor, "pre_insert_local_inventory") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = localinventory.InsertLocalInventoryRequest.pb(localinventory.InsertLocalInventoryRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = localinventory.LocalInventory.to_json(localinventory.LocalInventory()) + req.return_value.content = return_value + + request = localinventory.InsertLocalInventoryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = localinventory.LocalInventory() + post_with_metadata.return_value = localinventory.LocalInventory(), metadata + + client.insert_local_inventory(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_local_inventory_rest_bad_request(request_type=localinventory.DeleteLocalInventoryRequest): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/products/sample2/localInventories/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_local_inventory(request) + + +@pytest.mark.parametrize("request_type", [ + localinventory.DeleteLocalInventoryRequest, + dict, +]) +def test_delete_local_inventory_rest_call_success(request_type): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/products/sample2/localInventories/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = '' + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_local_inventory(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_local_inventory_rest_interceptors(null_interceptor): + transport = transports.LocalInventoryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LocalInventoryServiceRestInterceptor(), + ) + client = LocalInventoryServiceClient(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.LocalInventoryServiceRestInterceptor, "pre_delete_local_inventory") as pre: + pre.assert_not_called() + pb_message = localinventory.DeleteLocalInventoryRequest.pb(localinventory.DeleteLocalInventoryRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = localinventory.DeleteLocalInventoryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_local_inventory(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + +def test_initialize_client_w_rest(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_local_inventories_empty_call_rest(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + client.list_local_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = localinventory.ListLocalInventoriesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_insert_local_inventory_empty_call_rest(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_local_inventory), + '__call__') as call: + client.insert_local_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = localinventory.InsertLocalInventoryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_local_inventory_empty_call_rest(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__call__') as call: + client.delete_local_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = localinventory.DeleteLocalInventoryRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.LocalInventoryServiceGrpcTransport, + ) + +def test_local_inventory_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.LocalInventoryServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_local_inventory_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_inventories_v1.services.local_inventory_service.transports.LocalInventoryServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.LocalInventoryServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_local_inventories', + 'insert_local_inventory', + 'delete_local_inventory', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_local_inventory_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.shopping.merchant_inventories_v1.services.local_inventory_service.transports.LocalInventoryServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LocalInventoryServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/content', +), + quota_project_id="octopus", + ) + + +def test_local_inventory_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.shopping.merchant_inventories_v1.services.local_inventory_service.transports.LocalInventoryServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LocalInventoryServiceTransport() + adc.assert_called_once() + + +def test_local_inventory_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + LocalInventoryServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/content', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.LocalInventoryServiceGrpcTransport, + transports.LocalInventoryServiceGrpcAsyncIOTransport, + ], +) +def test_local_inventory_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/content',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.LocalInventoryServiceGrpcTransport, + transports.LocalInventoryServiceGrpcAsyncIOTransport, + transports.LocalInventoryServiceRestTransport, + ], +) +def test_local_inventory_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.LocalInventoryServiceGrpcTransport, grpc_helpers), + (transports.LocalInventoryServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_local_inventory_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "merchantapi.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/content', +), + scopes=["1", "2"], + default_host="merchantapi.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.LocalInventoryServiceGrpcTransport, transports.LocalInventoryServiceGrpcAsyncIOTransport]) +def test_local_inventory_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_local_inventory_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.LocalInventoryServiceRestTransport ( + 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", +]) +def test_local_inventory_service_host_no_port(transport_name): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='merchantapi.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'merchantapi.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://merchantapi.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_local_inventory_service_host_with_port(transport_name): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='merchantapi.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'merchantapi.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://merchantapi.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_local_inventory_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = LocalInventoryServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = LocalInventoryServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_local_inventories._session + session2 = client2.transport.list_local_inventories._session + assert session1 != session2 + session1 = client1.transport.insert_local_inventory._session + session2 = client2.transport.insert_local_inventory._session + assert session1 != session2 + session1 = client1.transport.delete_local_inventory._session + session2 = client2.transport.delete_local_inventory._session + assert session1 != session2 +def test_local_inventory_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.LocalInventoryServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_local_inventory_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.LocalInventoryServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.LocalInventoryServiceGrpcTransport, transports.LocalInventoryServiceGrpcAsyncIOTransport]) +def test_local_inventory_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.LocalInventoryServiceGrpcTransport, transports.LocalInventoryServiceGrpcAsyncIOTransport]) +def test_local_inventory_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_local_inventory_path(): + account = "squid" + product = "clam" + store_code = "whelk" + expected = "accounts/{account}/products/{product}/localInventories/{store_code}".format(account=account, product=product, store_code=store_code, ) + actual = LocalInventoryServiceClient.local_inventory_path(account, product, store_code) + assert expected == actual + + +def test_parse_local_inventory_path(): + expected = { + "account": "octopus", + "product": "oyster", + "store_code": "nudibranch", + } + path = LocalInventoryServiceClient.local_inventory_path(**expected) + + # Check that the path construction is reversible. + actual = LocalInventoryServiceClient.parse_local_inventory_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = LocalInventoryServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = LocalInventoryServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = LocalInventoryServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = LocalInventoryServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = LocalInventoryServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = LocalInventoryServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = LocalInventoryServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = LocalInventoryServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = LocalInventoryServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = LocalInventoryServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = LocalInventoryServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = LocalInventoryServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = LocalInventoryServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = LocalInventoryServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = LocalInventoryServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.LocalInventoryServiceTransport, '_prep_wrapped_messages') as prep: + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.LocalInventoryServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = LocalInventoryServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_transport_close_grpc(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport), + (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + 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=None, + ) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/merchant_inventories_v1/test_regional_inventory_service.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/merchant_inventories_v1/test_regional_inventory_service.py new file mode 100644 index 000000000000..1043a9504607 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/merchant_inventories_v1/test_regional_inventory_service.py @@ -0,0 +1,3632 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +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 proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +try: + from google.auth.aio import credentials as ga_credentials_async + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import 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 +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +from google.protobuf import timestamp_pb2 # type: ignore +from google.shopping.merchant_inventories_v1.services.regional_inventory_service import RegionalInventoryServiceAsyncClient +from google.shopping.merchant_inventories_v1.services.regional_inventory_service import RegionalInventoryServiceClient +from google.shopping.merchant_inventories_v1.services.regional_inventory_service import pagers +from google.shopping.merchant_inventories_v1.services.regional_inventory_service import transports +from google.shopping.merchant_inventories_v1.types import inventories_common +from google.shopping.merchant_inventories_v1.types import regionalinventory +from google.shopping.type.types import types +from google.type import interval_pb2 # type: ignore +import google.auth + + + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + +# 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 + +# 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 + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert RegionalInventoryServiceClient._get_default_mtls_endpoint(None) is None + assert RegionalInventoryServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert RegionalInventoryServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert RegionalInventoryServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert RegionalInventoryServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert RegionalInventoryServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert RegionalInventoryServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert RegionalInventoryServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert RegionalInventoryServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + RegionalInventoryServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert RegionalInventoryServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert RegionalInventoryServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert RegionalInventoryServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + RegionalInventoryServiceClient._read_environment_variables() + 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 RegionalInventoryServiceClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert RegionalInventoryServiceClient._get_client_cert_source(None, False) is None + assert RegionalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert RegionalInventoryServiceClient._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 RegionalInventoryServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert RegionalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(RegionalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceClient)) +@mock.patch.object(RegionalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = RegionalInventoryServiceClient._DEFAULT_UNIVERSE + default_endpoint = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert RegionalInventoryServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert RegionalInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + assert RegionalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert RegionalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "always") == RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + assert RegionalInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + assert RegionalInventoryServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert RegionalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + RegionalInventoryServiceClient._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 RegionalInventoryServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert RegionalInventoryServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert RegionalInventoryServiceClient._get_universe_domain(None, None) == RegionalInventoryServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + RegionalInventoryServiceClient._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) +]) +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) + client = RegionalInventoryServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + +@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") + client = RegionalInventoryServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + +@pytest.mark.parametrize("client_class,transport_name", [ + (RegionalInventoryServiceClient, "grpc"), + (RegionalInventoryServiceAsyncClient, "grpc_asyncio"), + (RegionalInventoryServiceClient, "rest"), +]) +def test_regional_inventory_service_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: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'merchantapi.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://merchantapi.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.RegionalInventoryServiceGrpcTransport, "grpc"), + (transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.RegionalInventoryServiceRestTransport, "rest"), +]) +def test_regional_inventory_service_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: + 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", [ + (RegionalInventoryServiceClient, "grpc"), + (RegionalInventoryServiceAsyncClient, "grpc_asyncio"), + (RegionalInventoryServiceClient, "rest"), +]) +def test_regional_inventory_service_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: + factory.return_value = creds + 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) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'merchantapi.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://merchantapi.googleapis.com' + ) + + +def test_regional_inventory_service_client_get_transport_class(): + transport = RegionalInventoryServiceClient.get_transport_class() + available_transports = [ + transports.RegionalInventoryServiceGrpcTransport, + transports.RegionalInventoryServiceRestTransport, + ] + assert transport in available_transports + + transport = RegionalInventoryServiceClient.get_transport_class("grpc") + assert transport == transports.RegionalInventoryServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc"), + (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest"), +]) +@mock.patch.object(RegionalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceClient)) +@mock.patch.object(RegionalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceAsyncClient)) +def test_regional_inventory_service_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(RegionalInventoryServiceClient, '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(RegionalInventoryServiceClient, '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: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + 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=None, + ) + + # 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: + 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), + 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=None, + ) + + # 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: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + 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=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) 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`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + 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: + 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), + 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", [ + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc", "true"), + (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc", "false"), + (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest", "true"), + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(RegionalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceClient)) +@mock.patch.object(RegionalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_regional_inventory_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, 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) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # 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): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # 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): + 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), + 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=None, + ) + + +@pytest.mark.parametrize("client_class", [ + RegionalInventoryServiceClient, RegionalInventoryServiceAsyncClient +]) +@mock.patch.object(RegionalInventoryServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegionalInventoryServiceClient)) +@mock.patch.object(RegionalInventoryServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegionalInventoryServiceAsyncClient)) +def test_regional_inventory_service_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) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + 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) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + 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 "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # 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): + 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() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) 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`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + RegionalInventoryServiceClient, RegionalInventoryServiceAsyncClient +]) +@mock.patch.object(RegionalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceClient)) +@mock.patch.object(RegionalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceAsyncClient)) +def test_regional_inventory_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = RegionalInventoryServiceClient._DEFAULT_UNIVERSE + default_endpoint = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = RegionalInventoryServiceClient._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()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + 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()) + 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) + + # 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. + options = client_options.ClientOptions() + 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()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc"), + (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest"), +]) +def test_regional_inventory_service_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: + 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), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc", grpc_helpers), + (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest", None), +]) +def test_regional_inventory_service_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" + ) + + 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), + 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=None, + ) + +def test_regional_inventory_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_inventories_v1.services.regional_inventory_service.transports.RegionalInventoryServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = RegionalInventoryServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + 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=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc", grpc_helpers), + (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_regional_inventory_service_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" + ) + + 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), + 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=None, + ) + + # 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: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "merchantapi.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/content', +), + scopes=None, + default_host="merchantapi.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + regionalinventory.ListRegionalInventoriesRequest, + dict, +]) +def test_list_regional_inventories(request_type, transport: str = 'grpc'): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regionalinventory.ListRegionalInventoriesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_regional_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = regionalinventory.ListRegionalInventoriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRegionalInventoriesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_regional_inventories_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = regionalinventory.ListRegionalInventoriesRequest( + 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_regional_inventories), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_regional_inventories(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == regionalinventory.ListRegionalInventoriesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_regional_inventories_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_regional_inventories in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_regional_inventories] = mock_rpc + request = {} + client.list_regional_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_regional_inventories(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_regional_inventories_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_regional_inventories 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_regional_inventories] = mock_rpc + + request = {} + await client.list_regional_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_regional_inventories(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_regional_inventories_async(transport: str = 'grpc_asyncio', request_type=regionalinventory.ListRegionalInventoriesRequest): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.ListRegionalInventoriesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_regional_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = regionalinventory.ListRegionalInventoriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRegionalInventoriesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_regional_inventories_async_from_dict(): + await test_list_regional_inventories_async(request_type=dict) + +def test_list_regional_inventories_field_headers(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = regionalinventory.ListRegionalInventoriesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + call.return_value = regionalinventory.ListRegionalInventoriesResponse() + client.list_regional_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_regional_inventories_field_headers_async(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = regionalinventory.ListRegionalInventoriesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.ListRegionalInventoriesResponse()) + await client.list_regional_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_regional_inventories_flattened(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regionalinventory.ListRegionalInventoriesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_regional_inventories( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_regional_inventories_flattened_error(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_regional_inventories( + regionalinventory.ListRegionalInventoriesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_regional_inventories_flattened_async(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regionalinventory.ListRegionalInventoriesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.ListRegionalInventoriesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_regional_inventories( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_regional_inventories_flattened_error_async(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_regional_inventories( + regionalinventory.ListRegionalInventoriesRequest(), + parent='parent_value', + ) + + +def test_list_regional_inventories_pager(transport_name: str = "grpc"): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + next_page_token='abc', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[], + next_page_token='def', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + ], + next_page_token='ghi', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_regional_inventories(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, regionalinventory.RegionalInventory) + for i in results) +def test_list_regional_inventories_pages(transport_name: str = "grpc"): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + next_page_token='abc', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[], + next_page_token='def', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + ], + next_page_token='ghi', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + ), + RuntimeError, + ) + pages = list(client.list_regional_inventories(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_regional_inventories_async_pager(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + next_page_token='abc', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[], + next_page_token='def', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + ], + next_page_token='ghi', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_regional_inventories(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, regionalinventory.RegionalInventory) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_regional_inventories_async_pages(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + next_page_token='abc', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[], + next_page_token='def', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + ], + next_page_token='ghi', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_regional_inventories(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + regionalinventory.InsertRegionalInventoryRequest, + dict, +]) +def test_insert_regional_inventory(request_type, transport: str = 'grpc'): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_regional_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regionalinventory.RegionalInventory( + name='name_value', + account=749, + region='region_value', + ) + response = client.insert_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = regionalinventory.InsertRegionalInventoryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, regionalinventory.RegionalInventory) + assert response.name == 'name_value' + assert response.account == 749 + assert response.region == 'region_value' + + +def test_insert_regional_inventory_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = regionalinventory.InsertRegionalInventoryRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_regional_inventory), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.insert_regional_inventory(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == regionalinventory.InsertRegionalInventoryRequest( + parent='parent_value', + ) + +def test_insert_regional_inventory_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.insert_regional_inventory in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.insert_regional_inventory] = mock_rpc + request = {} + client.insert_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.insert_regional_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_insert_regional_inventory_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.insert_regional_inventory 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.insert_regional_inventory] = mock_rpc + + request = {} + await client.insert_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.insert_regional_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_insert_regional_inventory_async(transport: str = 'grpc_asyncio', request_type=regionalinventory.InsertRegionalInventoryRequest): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_regional_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.RegionalInventory( + name='name_value', + account=749, + region='region_value', + )) + response = await client.insert_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = regionalinventory.InsertRegionalInventoryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, regionalinventory.RegionalInventory) + assert response.name == 'name_value' + assert response.account == 749 + assert response.region == 'region_value' + + +@pytest.mark.asyncio +async def test_insert_regional_inventory_async_from_dict(): + await test_insert_regional_inventory_async(request_type=dict) + +def test_insert_regional_inventory_field_headers(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = regionalinventory.InsertRegionalInventoryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_regional_inventory), + '__call__') as call: + call.return_value = regionalinventory.RegionalInventory() + client.insert_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_insert_regional_inventory_field_headers_async(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = regionalinventory.InsertRegionalInventoryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_regional_inventory), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.RegionalInventory()) + await client.insert_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + regionalinventory.DeleteRegionalInventoryRequest, + dict, +]) +def test_delete_regional_inventory(request_type, transport: str = 'grpc'): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = regionalinventory.DeleteRegionalInventoryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_regional_inventory_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = regionalinventory.DeleteRegionalInventoryRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_regional_inventory(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == regionalinventory.DeleteRegionalInventoryRequest( + name='name_value', + ) + +def test_delete_regional_inventory_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_regional_inventory in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_regional_inventory] = mock_rpc + request = {} + client.delete_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_regional_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_regional_inventory_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_regional_inventory 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_regional_inventory] = mock_rpc + + request = {} + await client.delete_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_regional_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_regional_inventory_async(transport: str = 'grpc_asyncio', request_type=regionalinventory.DeleteRegionalInventoryRequest): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = regionalinventory.DeleteRegionalInventoryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_regional_inventory_async_from_dict(): + await test_delete_regional_inventory_async(request_type=dict) + +def test_delete_regional_inventory_field_headers(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = regionalinventory.DeleteRegionalInventoryRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__call__') as call: + call.return_value = None + client.delete_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_regional_inventory_field_headers_async(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = regionalinventory.DeleteRegionalInventoryRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_regional_inventory_flattened(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__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_regional_inventory( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_regional_inventory_flattened_error(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_regional_inventory( + regionalinventory.DeleteRegionalInventoryRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_regional_inventory_flattened_async(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_regional_inventory( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_regional_inventory_flattened_error_async(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_regional_inventory( + regionalinventory.DeleteRegionalInventoryRequest(), + name='name_value', + ) + + +def test_list_regional_inventories_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_regional_inventories in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_regional_inventories] = mock_rpc + + request = {} + client.list_regional_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_regional_inventories(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_regional_inventories_rest_required_fields(request_type=regionalinventory.ListRegionalInventoriesRequest): + transport_class = transports.RegionalInventoryServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_regional_inventories._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_regional_inventories._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", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = regionalinventory.ListRegionalInventoriesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = regionalinventory.ListRegionalInventoriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_regional_inventories(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_regional_inventories_rest_unset_required_fields(): + transport = transports.RegionalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_regional_inventories._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_regional_inventories_rest_flattened(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = regionalinventory.ListRegionalInventoriesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1/products/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = regionalinventory.ListRegionalInventoriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_regional_inventories(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/inventories/v1/{parent=accounts/*/products/*}/regionalInventories" % client.transport._host, args[1]) + + +def test_list_regional_inventories_rest_flattened_error(transport: str = 'rest'): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_regional_inventories( + regionalinventory.ListRegionalInventoriesRequest(), + parent='parent_value', + ) + + +def test_list_regional_inventories_rest_pager(transport: str = 'rest'): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + next_page_token='abc', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[], + next_page_token='def', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + ], + next_page_token='ghi', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(regionalinventory.ListRegionalInventoriesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'accounts/sample1/products/sample2'} + + pager = client.list_regional_inventories(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, regionalinventory.RegionalInventory) + for i in results) + + pages = list(client.list_regional_inventories(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_insert_regional_inventory_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.insert_regional_inventory in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.insert_regional_inventory] = mock_rpc + + request = {} + client.insert_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.insert_regional_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_insert_regional_inventory_rest_required_fields(request_type=regionalinventory.InsertRegionalInventoryRequest): + transport_class = transports.RegionalInventoryServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).insert_regional_inventory._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).insert_regional_inventory._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = regionalinventory.RegionalInventory() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = regionalinventory.RegionalInventory.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.insert_regional_inventory(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_insert_regional_inventory_rest_unset_required_fields(): + transport = transports.RegionalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.insert_regional_inventory._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "regionalInventory", ))) + + +def test_delete_regional_inventory_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_regional_inventory in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_regional_inventory] = mock_rpc + + request = {} + client.delete_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_regional_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_regional_inventory_rest_required_fields(request_type=regionalinventory.DeleteRegionalInventoryRequest): + transport_class = transports.RegionalInventoryServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_regional_inventory._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_regional_inventory._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_regional_inventory(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_regional_inventory_rest_unset_required_fields(): + transport = transports.RegionalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_regional_inventory._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_regional_inventory_rest_flattened(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/products/sample2/regionalInventories/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_regional_inventory(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/inventories/v1/{name=accounts/*/products/*/regionalInventories/*}" % client.transport._host, args[1]) + + +def test_delete_regional_inventory_rest_flattened_error(transport: str = 'rest'): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_regional_inventory( + regionalinventory.DeleteRegionalInventoryRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RegionalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RegionalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionalInventoryServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RegionalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RegionalInventoryServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RegionalInventoryServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RegionalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionalInventoryServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RegionalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RegionalInventoryServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.RegionalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.RegionalInventoryServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.RegionalInventoryServiceGrpcTransport, + transports.RegionalInventoryServiceGrpcAsyncIOTransport, + transports.RegionalInventoryServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_kind_grpc(): + transport = RegionalInventoryServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_regional_inventories_empty_call_grpc(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + call.return_value = regionalinventory.ListRegionalInventoriesResponse() + client.list_regional_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regionalinventory.ListRegionalInventoriesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_insert_regional_inventory_empty_call_grpc(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_regional_inventory), + '__call__') as call: + call.return_value = regionalinventory.RegionalInventory() + client.insert_regional_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regionalinventory.InsertRegionalInventoryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_regional_inventory_empty_call_grpc(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__call__') as call: + call.return_value = None + client.delete_regional_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regionalinventory.DeleteRegionalInventoryRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = RegionalInventoryServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_regional_inventories_empty_call_grpc_asyncio(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.ListRegionalInventoriesResponse( + next_page_token='next_page_token_value', + )) + await client.list_regional_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regionalinventory.ListRegionalInventoriesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_insert_regional_inventory_empty_call_grpc_asyncio(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_regional_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.RegionalInventory( + name='name_value', + account=749, + region='region_value', + )) + await client.insert_regional_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regionalinventory.InsertRegionalInventoryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_regional_inventory_empty_call_grpc_asyncio(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_regional_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regionalinventory.DeleteRegionalInventoryRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = RegionalInventoryServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_regional_inventories_rest_bad_request(request_type=regionalinventory.ListRegionalInventoriesRequest): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/products/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_regional_inventories(request) + + +@pytest.mark.parametrize("request_type", [ + regionalinventory.ListRegionalInventoriesRequest, + dict, +]) +def test_list_regional_inventories_rest_call_success(request_type): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/products/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = regionalinventory.ListRegionalInventoriesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = regionalinventory.ListRegionalInventoriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_regional_inventories(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRegionalInventoriesPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_regional_inventories_rest_interceptors(null_interceptor): + transport = transports.RegionalInventoryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegionalInventoryServiceRestInterceptor(), + ) + client = RegionalInventoryServiceClient(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.RegionalInventoryServiceRestInterceptor, "post_list_regional_inventories") as post, \ + mock.patch.object(transports.RegionalInventoryServiceRestInterceptor, "post_list_regional_inventories_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.RegionalInventoryServiceRestInterceptor, "pre_list_regional_inventories") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = regionalinventory.ListRegionalInventoriesRequest.pb(regionalinventory.ListRegionalInventoriesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = regionalinventory.ListRegionalInventoriesResponse.to_json(regionalinventory.ListRegionalInventoriesResponse()) + req.return_value.content = return_value + + request = regionalinventory.ListRegionalInventoriesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = regionalinventory.ListRegionalInventoriesResponse() + post_with_metadata.return_value = regionalinventory.ListRegionalInventoriesResponse(), metadata + + client.list_regional_inventories(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_insert_regional_inventory_rest_bad_request(request_type=regionalinventory.InsertRegionalInventoryRequest): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/products/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.insert_regional_inventory(request) + + +@pytest.mark.parametrize("request_type", [ + regionalinventory.InsertRegionalInventoryRequest, + dict, +]) +def test_insert_regional_inventory_rest_call_success(request_type): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/products/sample2'} + request_init["regional_inventory"] = {'name': 'name_value', 'account': 749, 'region': 'region_value', 'regional_inventory_attributes': {'price': {'amount_micros': 1408, 'currency_code': 'currency_code_value'}, 'sale_price': {}, 'sale_price_effective_date': {'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}}, 'availability': 1}} + # 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 = regionalinventory.InsertRegionalInventoryRequest.meta.fields["regional_inventory"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["regional_inventory"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["regional_inventory"][field])): + del request_init["regional_inventory"][field][i][subfield] + else: + del request_init["regional_inventory"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = regionalinventory.RegionalInventory( + name='name_value', + account=749, + region='region_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = regionalinventory.RegionalInventory.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.insert_regional_inventory(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, regionalinventory.RegionalInventory) + assert response.name == 'name_value' + assert response.account == 749 + assert response.region == 'region_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_insert_regional_inventory_rest_interceptors(null_interceptor): + transport = transports.RegionalInventoryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegionalInventoryServiceRestInterceptor(), + ) + client = RegionalInventoryServiceClient(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.RegionalInventoryServiceRestInterceptor, "post_insert_regional_inventory") as post, \ + mock.patch.object(transports.RegionalInventoryServiceRestInterceptor, "post_insert_regional_inventory_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.RegionalInventoryServiceRestInterceptor, "pre_insert_regional_inventory") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = regionalinventory.InsertRegionalInventoryRequest.pb(regionalinventory.InsertRegionalInventoryRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = regionalinventory.RegionalInventory.to_json(regionalinventory.RegionalInventory()) + req.return_value.content = return_value + + request = regionalinventory.InsertRegionalInventoryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = regionalinventory.RegionalInventory() + post_with_metadata.return_value = regionalinventory.RegionalInventory(), metadata + + client.insert_regional_inventory(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_regional_inventory_rest_bad_request(request_type=regionalinventory.DeleteRegionalInventoryRequest): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/products/sample2/regionalInventories/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_regional_inventory(request) + + +@pytest.mark.parametrize("request_type", [ + regionalinventory.DeleteRegionalInventoryRequest, + dict, +]) +def test_delete_regional_inventory_rest_call_success(request_type): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/products/sample2/regionalInventories/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = '' + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_regional_inventory(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_regional_inventory_rest_interceptors(null_interceptor): + transport = transports.RegionalInventoryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegionalInventoryServiceRestInterceptor(), + ) + client = RegionalInventoryServiceClient(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.RegionalInventoryServiceRestInterceptor, "pre_delete_regional_inventory") as pre: + pre.assert_not_called() + pb_message = regionalinventory.DeleteRegionalInventoryRequest.pb(regionalinventory.DeleteRegionalInventoryRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = regionalinventory.DeleteRegionalInventoryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_regional_inventory(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + +def test_initialize_client_w_rest(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_regional_inventories_empty_call_rest(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + client.list_regional_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regionalinventory.ListRegionalInventoriesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_insert_regional_inventory_empty_call_rest(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_regional_inventory), + '__call__') as call: + client.insert_regional_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regionalinventory.InsertRegionalInventoryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_regional_inventory_empty_call_rest(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__call__') as call: + client.delete_regional_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regionalinventory.DeleteRegionalInventoryRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.RegionalInventoryServiceGrpcTransport, + ) + +def test_regional_inventory_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RegionalInventoryServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_regional_inventory_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_inventories_v1.services.regional_inventory_service.transports.RegionalInventoryServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.RegionalInventoryServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_regional_inventories', + 'insert_regional_inventory', + 'delete_regional_inventory', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_regional_inventory_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.shopping.merchant_inventories_v1.services.regional_inventory_service.transports.RegionalInventoryServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionalInventoryServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/content', +), + quota_project_id="octopus", + ) + + +def test_regional_inventory_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.shopping.merchant_inventories_v1.services.regional_inventory_service.transports.RegionalInventoryServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionalInventoryServiceTransport() + adc.assert_called_once() + + +def test_regional_inventory_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RegionalInventoryServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/content', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RegionalInventoryServiceGrpcTransport, + transports.RegionalInventoryServiceGrpcAsyncIOTransport, + ], +) +def test_regional_inventory_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/content',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RegionalInventoryServiceGrpcTransport, + transports.RegionalInventoryServiceGrpcAsyncIOTransport, + transports.RegionalInventoryServiceRestTransport, + ], +) +def test_regional_inventory_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.RegionalInventoryServiceGrpcTransport, grpc_helpers), + (transports.RegionalInventoryServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_regional_inventory_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "merchantapi.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/content', +), + scopes=["1", "2"], + default_host="merchantapi.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.RegionalInventoryServiceGrpcTransport, transports.RegionalInventoryServiceGrpcAsyncIOTransport]) +def test_regional_inventory_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_regional_inventory_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.RegionalInventoryServiceRestTransport ( + 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", +]) +def test_regional_inventory_service_host_no_port(transport_name): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='merchantapi.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'merchantapi.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://merchantapi.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_regional_inventory_service_host_with_port(transport_name): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='merchantapi.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'merchantapi.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://merchantapi.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_regional_inventory_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = RegionalInventoryServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = RegionalInventoryServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_regional_inventories._session + session2 = client2.transport.list_regional_inventories._session + assert session1 != session2 + session1 = client1.transport.insert_regional_inventory._session + session2 = client2.transport.insert_regional_inventory._session + assert session1 != session2 + session1 = client1.transport.delete_regional_inventory._session + session2 = client2.transport.delete_regional_inventory._session + assert session1 != session2 +def test_regional_inventory_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RegionalInventoryServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_regional_inventory_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RegionalInventoryServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.RegionalInventoryServiceGrpcTransport, transports.RegionalInventoryServiceGrpcAsyncIOTransport]) +def test_regional_inventory_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.RegionalInventoryServiceGrpcTransport, transports.RegionalInventoryServiceGrpcAsyncIOTransport]) +def test_regional_inventory_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_regional_inventory_path(): + account = "squid" + product = "clam" + region = "whelk" + expected = "accounts/{account}/products/{product}/regionalInventories/{region}".format(account=account, product=product, region=region, ) + actual = RegionalInventoryServiceClient.regional_inventory_path(account, product, region) + assert expected == actual + + +def test_parse_regional_inventory_path(): + expected = { + "account": "octopus", + "product": "oyster", + "region": "nudibranch", + } + path = RegionalInventoryServiceClient.regional_inventory_path(**expected) + + # Check that the path construction is reversible. + actual = RegionalInventoryServiceClient.parse_regional_inventory_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = RegionalInventoryServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = RegionalInventoryServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RegionalInventoryServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = RegionalInventoryServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = RegionalInventoryServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RegionalInventoryServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = RegionalInventoryServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = RegionalInventoryServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RegionalInventoryServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = RegionalInventoryServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = RegionalInventoryServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RegionalInventoryServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = RegionalInventoryServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = RegionalInventoryServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RegionalInventoryServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.RegionalInventoryServiceTransport, '_prep_wrapped_messages') as prep: + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.RegionalInventoryServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = RegionalInventoryServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_transport_close_grpc(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport), + (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + 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=None, + ) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/.coveragerc b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/.coveragerc new file mode 100644 index 000000000000..b3835b541d48 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/shopping/merchant_inventories/__init__.py + google/shopping/merchant_inventories/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/.flake8 b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/.flake8 new file mode 100644 index 000000000000..90316de21489 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/.flake8 @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +[flake8] +# TODO(https://github.com/googleapis/gapic-generator-python/issues/2333): +# Resolve flake8 lint issues +ignore = E203, E231, E266, E501, W503 +exclude = + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2333): + # Ensure that generated code passes flake8 lint + **/gapic/** + **/services/** + **/types/** + # Exclude Protobuf gencode + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/LICENSE b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/MANIFEST.in b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/MANIFEST.in new file mode 100644 index 000000000000..dae249ec8976 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/MANIFEST.in @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +include README.rst LICENSE +recursive-include google *.py *.pyi *.json *.proto py.typed +recursive-include tests * +global-exclude *.py[co] +global-exclude __pycache__ diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/README.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/README.rst new file mode 100644 index 000000000000..373e5600ce98 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/README.rst @@ -0,0 +1,143 @@ +Python Client for Google Shopping Merchant Inventories API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Shopping Merchant Inventories API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library + + +Logging +------- + +This library uses the standard Python :code:`logging` functionality to log some RPC events that could be of interest for debugging and monitoring purposes. +Note the following: + +#. Logs may contain sensitive information. Take care to **restrict access to the logs** if they are saved, whether it be on local storage or on Google Cloud Logging. +#. Google may refine the occurrence, level, and content of various log messages in this library without flagging such changes as breaking. **Do not depend on immutability of the logging events**. +#. By default, the logging events from this library are not handled. You must **explicitly configure log handling** using one of the mechanisms below. + + +Simple, environment-based configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To enable logging for this library without any changes in your code, set the :code:`GOOGLE_SDK_PYTHON_LOGGING_SCOPE` environment variable to a valid Google +logging scope. This configures handling of logging events (at level :code:`logging.DEBUG` or higher) from this library in a default manner, emitting the logged +messages in a structured format. It does not currently allow customizing the logging levels captured nor the handlers, formatters, etc. used for any logging +event. + +A logging scope is a period-separated namespace that begins with :code:`google`, identifying the Python module or package to log. + +- Valid logging scopes: :code:`google`, :code:`google.cloud.asset.v1`, :code:`google.api`, :code:`google.auth`, etc. +- Invalid logging scopes: :code:`foo`, :code:`123`, etc. + +**NOTE**: If the logging scope is invalid, the library does not set up any logging handlers. + + +Examples +^^^^^^^^ + +- Enabling the default handler for all Google-based loggers + +.. code-block:: console + + export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google + +- Enabling the default handler for a specific Google module (for a client library called :code:`library_v1`): + +.. code-block:: console + + export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google.cloud.library_v1 + + +Advanced, code-based configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can also configure a valid logging scope using Python's standard `logging` mechanism. + + +Examples +^^^^^^^^ + +- Configuring a handler for all Google-based loggers + +.. code-block:: python + + import logging + + from google.cloud.translate_v3 import translate + + base_logger = logging.getLogger("google") + base_logger.addHandler(logging.StreamHandler()) + base_logger.setLevel(logging.DEBUG) + +- Configuring a handler for a specific Google module (for a client library called :code:`library_v1`): + +.. code-block:: python + + import logging + + from google.cloud.translate_v3 import translate + + base_logger = logging.getLogger("google.cloud.library_v1") + base_logger.addHandler(logging.StreamHandler()) + base_logger.setLevel(logging.DEBUG) + + +Logging details +~~~~~~~~~~~~~~~ + +#. Regardless of which of the mechanisms above you use to configure logging for this library, by default logging events are not propagated up to the root + logger from the `google`-level logger. If you need the events to be propagated to the root logger, you must explicitly set + :code:`logging.getLogger("google").propagate = True` in your code. +#. You can mix the different logging configurations above for different Google modules. For example, you may want use a code-based logging configuration for + one library, but decide you need to also set up environment-based logging configuration for another library. + + #. If you attempt to use both code-based and environment-based configuration for the same module, the environment-based configuration will be ineffectual + if the code -based configuration gets applied first. + +#. The Google-specific logging configurations (default handlers for environment-based configuration; not propagating logging events to the root logger) get + executed the first time *any* client library is instantiated in your application, and only if the affected loggers have not been previously configured. + (This is the reason for 2.i. above.) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/_static/custom.css b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/_static/custom.css new file mode 100644 index 000000000000..b0a295464b23 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/_static/custom.css @@ -0,0 +1,20 @@ +div#python2-eol { + border-color: red; + border-width: medium; +} + +/* Ensure minimum width for 'Parameters' / 'Returns' column */ +dl.field-list > dt { + min-width: 100px +} + +/* Insert space between methods for readability */ +dl.method { + padding-top: 10px; + padding-bottom: 10px +} + +/* Insert empty space between classes */ +dl.class { + padding-bottom: 50px +} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/_templates/layout.html b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/_templates/layout.html new file mode 100644 index 000000000000..95e9c77fcfe1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/_templates/layout.html @@ -0,0 +1,50 @@ + +{% extends "!layout.html" %} +{%- block content %} +{%- if theme_fixed_sidebar|lower == 'true' %} +
+ {{ sidebar() }} + {%- block document %} +
+ {%- if render_sidebar %} +
+ {%- endif %} + + {%- block relbar_top %} + {%- if theme_show_relbar_top|tobool %} + + {%- endif %} + {% endblock %} + +
+
+ As of January 1, 2020 this library no longer supports Python 2 on the latest released version. + Library versions released prior to that date will continue to be available. For more information please + visit Python 2 support on Google Cloud. +
+ {% block body %} {% endblock %} +
+ + {%- block relbar_bottom %} + {%- if theme_show_relbar_bottom|tobool %} + + {%- endif %} + {% endblock %} + + {%- if render_sidebar %} +
+ {%- endif %} +
+ {%- endblock %} +
+
+{%- else %} +{{ super() }} +{%- endif %} +{%- endblock %} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/conf.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/conf.py new file mode 100644 index 000000000000..b4a1101f35ed --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/conf.py @@ -0,0 +1,385 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-shopping-merchant-inventories documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# 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 +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +# For plugins that can not read conf.py. +# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 +sys.path.insert(0, os.path.abspath(".")) + +__version__ = "" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.5.0" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.doctest", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", + "recommonmark", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_options = {"members": True} +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# source_suffix = ['.rst', '.md'] +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-shopping-merchant-inventories" +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 +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = [ + "_build", + "**/.nox/**/*", + "samples/AUTHORING_GUIDE.md", + "samples/CONTRIBUTING.md", + "samples/snippets/README.rst", +] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Shopping Client Libraries for google-shopping-merchant-inventories", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-shopping-merchant-inventories-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-shopping-merchant-inventories.tex", + u"google-shopping-merchant-inventories Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-shopping-merchant-inventories", + "google-shopping-merchant-inventories Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-shopping-merchant-inventories", + "google-shopping-merchant-inventories Documentation", + author, + "google-shopping-merchant-inventories", + "google-shopping-merchant-inventories Library", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("https://python.readthedocs.org/en/latest/", None), + "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None), + "google.api_core": ( + "https://googleapis.dev/python/google-api-core/latest/", + None, + ), + "grpc": ("https://grpc.github.io/grpc/python/", None), + "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/index.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/index.rst new file mode 100644 index 000000000000..d9a85dd953d7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/index.rst @@ -0,0 +1,10 @@ +.. include:: multiprocessing.rst + + +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + merchant_inventories_v1beta/services_ + merchant_inventories_v1beta/types_ diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/local_inventory_service.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/local_inventory_service.rst new file mode 100644 index 000000000000..d8e5a2b05114 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/local_inventory_service.rst @@ -0,0 +1,10 @@ +LocalInventoryService +--------------------------------------- + +.. automodule:: google.shopping.merchant_inventories_v1beta.services.local_inventory_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_inventories_v1beta.services.local_inventory_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/regional_inventory_service.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/regional_inventory_service.rst new file mode 100644 index 000000000000..d23b466a2398 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/regional_inventory_service.rst @@ -0,0 +1,10 @@ +RegionalInventoryService +------------------------------------------ + +.. automodule:: google.shopping.merchant_inventories_v1beta.services.regional_inventory_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/services_.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/services_.rst new file mode 100644 index 000000000000..7bdd71de9b95 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/services_.rst @@ -0,0 +1,7 @@ +Services for Google Shopping Merchant Inventories v1beta API +============================================================ +.. toctree:: + :maxdepth: 2 + + local_inventory_service + regional_inventory_service diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/types_.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/types_.rst new file mode 100644 index 000000000000..2bd5b6e3cb01 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/types_.rst @@ -0,0 +1,6 @@ +Types for Google Shopping Merchant Inventories v1beta API +========================================================= + +.. automodule:: google.shopping.merchant_inventories_v1beta.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/multiprocessing.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/multiprocessing.rst new file mode 100644 index 000000000000..536d17b2ea65 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/multiprocessing.rst @@ -0,0 +1,7 @@ +.. note:: + + Because this client uses :mod:`grpc` library, it is safe to + share instances across threads. In multiprocessing scenarios, the best + practice is to create client instances *after* the invocation of + :func:`os.fork` by :class:`multiprocessing.pool.Pool` or + :class:`multiprocessing.Process`. diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/__init__.py new file mode 100644 index 000000000000..381ccc39f545 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/__init__.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.shopping.merchant_inventories import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.shopping.merchant_inventories_v1beta.services.local_inventory_service.client import LocalInventoryServiceClient +from google.shopping.merchant_inventories_v1beta.services.local_inventory_service.async_client import LocalInventoryServiceAsyncClient +from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.client import RegionalInventoryServiceClient +from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.async_client import RegionalInventoryServiceAsyncClient + +from google.shopping.merchant_inventories_v1beta.types.localinventory import DeleteLocalInventoryRequest +from google.shopping.merchant_inventories_v1beta.types.localinventory import InsertLocalInventoryRequest +from google.shopping.merchant_inventories_v1beta.types.localinventory import ListLocalInventoriesRequest +from google.shopping.merchant_inventories_v1beta.types.localinventory import ListLocalInventoriesResponse +from google.shopping.merchant_inventories_v1beta.types.localinventory import LocalInventory +from google.shopping.merchant_inventories_v1beta.types.regionalinventory import DeleteRegionalInventoryRequest +from google.shopping.merchant_inventories_v1beta.types.regionalinventory import InsertRegionalInventoryRequest +from google.shopping.merchant_inventories_v1beta.types.regionalinventory import ListRegionalInventoriesRequest +from google.shopping.merchant_inventories_v1beta.types.regionalinventory import ListRegionalInventoriesResponse +from google.shopping.merchant_inventories_v1beta.types.regionalinventory import RegionalInventory + +__all__ = ('LocalInventoryServiceClient', + 'LocalInventoryServiceAsyncClient', + 'RegionalInventoryServiceClient', + 'RegionalInventoryServiceAsyncClient', + 'DeleteLocalInventoryRequest', + 'InsertLocalInventoryRequest', + 'ListLocalInventoriesRequest', + 'ListLocalInventoriesResponse', + 'LocalInventory', + 'DeleteRegionalInventoryRequest', + 'InsertRegionalInventoryRequest', + 'ListRegionalInventoriesRequest', + 'ListRegionalInventoriesResponse', + 'RegionalInventory', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/gapic_version.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/gapic_version.py new file mode 100644 index 000000000000..20a9cd975b02 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/py.typed b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/py.typed new file mode 100644 index 000000000000..993f00a7e3c3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-shopping-merchant-inventories package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/__init__.py new file mode 100644 index 000000000000..a26ccce0e474 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/__init__.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.shopping.merchant_inventories_v1beta import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.local_inventory_service import LocalInventoryServiceClient +from .services.local_inventory_service import LocalInventoryServiceAsyncClient +from .services.regional_inventory_service import RegionalInventoryServiceClient +from .services.regional_inventory_service import RegionalInventoryServiceAsyncClient + +from .types.localinventory import DeleteLocalInventoryRequest +from .types.localinventory import InsertLocalInventoryRequest +from .types.localinventory import ListLocalInventoriesRequest +from .types.localinventory import ListLocalInventoriesResponse +from .types.localinventory import LocalInventory +from .types.regionalinventory import DeleteRegionalInventoryRequest +from .types.regionalinventory import InsertRegionalInventoryRequest +from .types.regionalinventory import ListRegionalInventoriesRequest +from .types.regionalinventory import ListRegionalInventoriesResponse +from .types.regionalinventory import RegionalInventory + +__all__ = ( + 'LocalInventoryServiceAsyncClient', + 'RegionalInventoryServiceAsyncClient', +'DeleteLocalInventoryRequest', +'DeleteRegionalInventoryRequest', +'InsertLocalInventoryRequest', +'InsertRegionalInventoryRequest', +'ListLocalInventoriesRequest', +'ListLocalInventoriesResponse', +'ListRegionalInventoriesRequest', +'ListRegionalInventoriesResponse', +'LocalInventory', +'LocalInventoryServiceClient', +'RegionalInventory', +'RegionalInventoryServiceClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_metadata.json b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_metadata.json new file mode 100644 index 000000000000..dca053900305 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_metadata.json @@ -0,0 +1,137 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.shopping.merchant_inventories_v1beta", + "protoPackage": "google.shopping.merchant.inventories.v1beta", + "schema": "1.0", + "services": { + "LocalInventoryService": { + "clients": { + "grpc": { + "libraryClient": "LocalInventoryServiceClient", + "rpcs": { + "DeleteLocalInventory": { + "methods": [ + "delete_local_inventory" + ] + }, + "InsertLocalInventory": { + "methods": [ + "insert_local_inventory" + ] + }, + "ListLocalInventories": { + "methods": [ + "list_local_inventories" + ] + } + } + }, + "grpc-async": { + "libraryClient": "LocalInventoryServiceAsyncClient", + "rpcs": { + "DeleteLocalInventory": { + "methods": [ + "delete_local_inventory" + ] + }, + "InsertLocalInventory": { + "methods": [ + "insert_local_inventory" + ] + }, + "ListLocalInventories": { + "methods": [ + "list_local_inventories" + ] + } + } + }, + "rest": { + "libraryClient": "LocalInventoryServiceClient", + "rpcs": { + "DeleteLocalInventory": { + "methods": [ + "delete_local_inventory" + ] + }, + "InsertLocalInventory": { + "methods": [ + "insert_local_inventory" + ] + }, + "ListLocalInventories": { + "methods": [ + "list_local_inventories" + ] + } + } + } + } + }, + "RegionalInventoryService": { + "clients": { + "grpc": { + "libraryClient": "RegionalInventoryServiceClient", + "rpcs": { + "DeleteRegionalInventory": { + "methods": [ + "delete_regional_inventory" + ] + }, + "InsertRegionalInventory": { + "methods": [ + "insert_regional_inventory" + ] + }, + "ListRegionalInventories": { + "methods": [ + "list_regional_inventories" + ] + } + } + }, + "grpc-async": { + "libraryClient": "RegionalInventoryServiceAsyncClient", + "rpcs": { + "DeleteRegionalInventory": { + "methods": [ + "delete_regional_inventory" + ] + }, + "InsertRegionalInventory": { + "methods": [ + "insert_regional_inventory" + ] + }, + "ListRegionalInventories": { + "methods": [ + "list_regional_inventories" + ] + } + } + }, + "rest": { + "libraryClient": "RegionalInventoryServiceClient", + "rpcs": { + "DeleteRegionalInventory": { + "methods": [ + "delete_regional_inventory" + ] + }, + "InsertRegionalInventory": { + "methods": [ + "insert_regional_inventory" + ] + }, + "ListRegionalInventories": { + "methods": [ + "list_regional_inventories" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_version.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_version.py new file mode 100644 index 000000000000..20a9cd975b02 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/py.typed b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/py.typed new file mode 100644 index 000000000000..993f00a7e3c3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-shopping-merchant-inventories package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/__init__.py new file mode 100644 index 000000000000..cbf94b283c70 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/__init__.py new file mode 100644 index 000000000000..4b805a80aace --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import LocalInventoryServiceClient +from .async_client import LocalInventoryServiceAsyncClient + +__all__ = ( + 'LocalInventoryServiceClient', + 'LocalInventoryServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/async_client.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/async_client.py new file mode 100644 index 000000000000..582b1f5798c7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/async_client.py @@ -0,0 +1,591 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import 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.shopping.merchant_inventories_v1beta 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.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + + +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.shopping.merchant_inventories_v1beta.services.local_inventory_service import pagers +from google.shopping.merchant_inventories_v1beta.types import localinventory +from google.shopping.type.types import types +from google.type import interval_pb2 # type: ignore +from .transports.base import LocalInventoryServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import LocalInventoryServiceGrpcAsyncIOTransport +from .client import LocalInventoryServiceClient + +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 LocalInventoryServiceAsyncClient: + """Service to manage local inventory for products""" + + _client: LocalInventoryServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = LocalInventoryServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = LocalInventoryServiceClient._DEFAULT_UNIVERSE + + local_inventory_path = staticmethod(LocalInventoryServiceClient.local_inventory_path) + parse_local_inventory_path = staticmethod(LocalInventoryServiceClient.parse_local_inventory_path) + common_billing_account_path = staticmethod(LocalInventoryServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(LocalInventoryServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(LocalInventoryServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(LocalInventoryServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(LocalInventoryServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(LocalInventoryServiceClient.parse_common_organization_path) + common_project_path = staticmethod(LocalInventoryServiceClient.common_project_path) + parse_common_project_path = staticmethod(LocalInventoryServiceClient.parse_common_project_path) + common_location_path = staticmethod(LocalInventoryServiceClient.common_location_path) + parse_common_location_path = staticmethod(LocalInventoryServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + LocalInventoryServiceAsyncClient: The constructed client. + """ + return LocalInventoryServiceClient.from_service_account_info.__func__(LocalInventoryServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + LocalInventoryServiceAsyncClient: The constructed client. + """ + return LocalInventoryServiceClient.from_service_account_file.__func__(LocalInventoryServiceAsyncClient, 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): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return LocalInventoryServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> LocalInventoryServiceTransport: + """Returns the transport used by the client instance. + + Returns: + LocalInventoryServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = LocalInventoryServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, LocalInventoryServiceTransport, Callable[..., LocalInventoryServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the local inventory service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,LocalInventoryServiceTransport,Callable[..., LocalInventoryServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the LocalInventoryServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = LocalInventoryServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.shopping.merchant.inventories_v1beta.LocalInventoryServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._client._transport, "_credentials") else { + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "credentialsType": None, + } + ) + + async def list_local_inventories(self, + request: Optional[Union[localinventory.ListLocalInventoriesRequest, 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.ListLocalInventoriesAsyncPager: + r"""Lists the ``LocalInventory`` resources for the given product in + your merchant account. The response might contain fewer items + than specified by ``pageSize``. If ``pageToken`` was returned in + previous request, it can be used to obtain additional results. + + ``LocalInventory`` resources are listed per product for a given + account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1beta + + async def sample_list_local_inventories(): + # Create a client + client = merchant_inventories_v1beta.LocalInventoryServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.ListLocalInventoriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_local_inventories(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesRequest, dict]]): + The request object. Request message for the ``ListLocalInventories`` method. + parent (:class:`str`): + Required. The ``name`` of the parent product to list + local inventories for. Format: + ``accounts/{account}/products/{product}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.shopping.merchant_inventories_v1beta.services.local_inventory_service.pagers.ListLocalInventoriesAsyncPager: + Response message for the ListLocalInventories method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, localinventory.ListLocalInventoriesRequest): + request = localinventory.ListLocalInventoriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_local_inventories] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListLocalInventoriesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def insert_local_inventory(self, + request: Optional[Union[localinventory.InsertLocalInventoryRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> localinventory.LocalInventory: + r"""Inserts a ``LocalInventory`` resource to a product in your + merchant account. + + Replaces the full ``LocalInventory`` resource if an entry with + the same + [``storeCode``][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code] + already exists for the product. + + It might take up to 30 minutes for the new or updated + ``LocalInventory`` resource to appear in products. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1beta + + async def sample_insert_local_inventory(): + # Create a client + client = merchant_inventories_v1beta.LocalInventoryServiceAsyncClient() + + # Initialize request argument(s) + local_inventory = merchant_inventories_v1beta.LocalInventory() + local_inventory.store_code = "store_code_value" + + request = merchant_inventories_v1beta.InsertLocalInventoryRequest( + parent="parent_value", + local_inventory=local_inventory, + ) + + # Make the request + response = await client.insert_local_inventory(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_inventories_v1beta.types.InsertLocalInventoryRequest, dict]]): + The request object. Request message for the ``InsertLocalInventory`` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.shopping.merchant_inventories_v1beta.types.LocalInventory: + Local inventory information for the product. Represents in-store information + for a specific product at the store specified by + [storeCode][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code]. + For a list of all accepted attribute values, see the + [local product inventory data + specification](\ https://support.google.com/merchants/answer/3061342). + + """ + # Create or coerce a protobuf request object. + # - 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, localinventory.InsertLocalInventoryRequest): + request = localinventory.InsertLocalInventoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.insert_local_inventory] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_local_inventory(self, + request: Optional[Union[localinventory.DeleteLocalInventoryRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified ``LocalInventory`` from the given product + in your merchant account. It might take a up to an hour for the + ``LocalInventory`` to be deleted from the specific product. Once + you have received a successful delete response, wait for that + period before attempting a delete again. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1beta + + async def sample_delete_local_inventory(): + # Create a client + client = merchant_inventories_v1beta.LocalInventoryServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.DeleteLocalInventoryRequest( + name="name_value", + ) + + # Make the request + await client.delete_local_inventory(request=request) + + Args: + request (Optional[Union[google.shopping.merchant_inventories_v1beta.types.DeleteLocalInventoryRequest, dict]]): + The request object. Request message for the ``DeleteLocalInventory`` method. + name (:class:`str`): + Required. The name of the local inventory for the given + product to delete. Format: + ``accounts/{account}/products/{product}/localInventories/{store_code}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, localinventory.DeleteLocalInventoryRequest): + request = localinventory.DeleteLocalInventoryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_local_inventory] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self) -> "LocalInventoryServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ( + "LocalInventoryServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/client.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/client.py new file mode 100644 index 000000000000..0e39530e77d2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/client.py @@ -0,0 +1,950 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.shopping.merchant_inventories_v1beta 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.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 + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.shopping.merchant_inventories_v1beta.services.local_inventory_service import pagers +from google.shopping.merchant_inventories_v1beta.types import localinventory +from google.shopping.type.types import types +from google.type import interval_pb2 # type: ignore +from .transports.base import LocalInventoryServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import LocalInventoryServiceGrpcTransport +from .transports.grpc_asyncio import LocalInventoryServiceGrpcAsyncIOTransport +from .transports.rest import LocalInventoryServiceRestTransport + + +class LocalInventoryServiceClientMeta(type): + """Metaclass for the LocalInventoryService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[LocalInventoryServiceTransport]] + _transport_registry["grpc"] = LocalInventoryServiceGrpcTransport + _transport_registry["grpc_asyncio"] = LocalInventoryServiceGrpcAsyncIOTransport + _transport_registry["rest"] = LocalInventoryServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[LocalInventoryServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class LocalInventoryServiceClient(metaclass=LocalInventoryServiceClientMeta): + """Service to manage local inventory for products""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "merchantapi.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "merchantapi.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + LocalInventoryServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + LocalInventoryServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> LocalInventoryServiceTransport: + """Returns the transport used by the client instance. + + Returns: + LocalInventoryServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def local_inventory_path(account: str,product: str,store_code: str,) -> str: + """Returns a fully-qualified local_inventory string.""" + return "accounts/{account}/products/{product}/localInventories/{store_code}".format(account=account, product=product, store_code=store_code, ) + + @staticmethod + def parse_local_inventory_path(path: str) -> Dict[str,str]: + """Parses a local_inventory path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/products/(?P.+?)/localInventories/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + 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: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + 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) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "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 + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_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): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = LocalInventoryServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = LocalInventoryServiceClient._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: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = LocalInventoryServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + 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]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, LocalInventoryServiceTransport, Callable[..., LocalInventoryServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the local inventory service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,LocalInventoryServiceTransport,Callable[..., LocalInventoryServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the LocalInventoryServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + 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) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = LocalInventoryServiceClient._read_environment_variables() + self._client_cert_source = LocalInventoryServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = LocalInventoryServiceClient._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 + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + 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") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, LocalInventoryServiceTransport) + if transport_provided: + # transport is a LocalInventoryServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + 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." + ) + self._transport = cast(LocalInventoryServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + LocalInventoryServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + 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) + + transport_init: Union[Type[LocalInventoryServiceTransport], Callable[..., LocalInventoryServiceTransport]] = ( + LocalInventoryServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., LocalInventoryServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "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 { + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "credentialsType": None, + } + ) + + def list_local_inventories(self, + request: Optional[Union[localinventory.ListLocalInventoriesRequest, 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.ListLocalInventoriesPager: + r"""Lists the ``LocalInventory`` resources for the given product in + your merchant account. The response might contain fewer items + than specified by ``pageSize``. If ``pageToken`` was returned in + previous request, it can be used to obtain additional results. + + ``LocalInventory`` resources are listed per product for a given + account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1beta + + def sample_list_local_inventories(): + # Create a client + client = merchant_inventories_v1beta.LocalInventoryServiceClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.ListLocalInventoriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_local_inventories(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesRequest, dict]): + The request object. Request message for the ``ListLocalInventories`` method. + parent (str): + Required. The ``name`` of the parent product to list + local inventories for. Format: + ``accounts/{account}/products/{product}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.shopping.merchant_inventories_v1beta.services.local_inventory_service.pagers.ListLocalInventoriesPager: + Response message for the ListLocalInventories method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, localinventory.ListLocalInventoriesRequest): + request = localinventory.ListLocalInventoriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_local_inventories] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListLocalInventoriesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def insert_local_inventory(self, + request: Optional[Union[localinventory.InsertLocalInventoryRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> localinventory.LocalInventory: + r"""Inserts a ``LocalInventory`` resource to a product in your + merchant account. + + Replaces the full ``LocalInventory`` resource if an entry with + the same + [``storeCode``][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code] + already exists for the product. + + It might take up to 30 minutes for the new or updated + ``LocalInventory`` resource to appear in products. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1beta + + def sample_insert_local_inventory(): + # Create a client + client = merchant_inventories_v1beta.LocalInventoryServiceClient() + + # Initialize request argument(s) + local_inventory = merchant_inventories_v1beta.LocalInventory() + local_inventory.store_code = "store_code_value" + + request = merchant_inventories_v1beta.InsertLocalInventoryRequest( + parent="parent_value", + local_inventory=local_inventory, + ) + + # Make the request + response = client.insert_local_inventory(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_inventories_v1beta.types.InsertLocalInventoryRequest, dict]): + The request object. Request message for the ``InsertLocalInventory`` 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: + google.shopping.merchant_inventories_v1beta.types.LocalInventory: + Local inventory information for the product. Represents in-store information + for a specific product at the store specified by + [storeCode][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code]. + For a list of all accepted attribute values, see the + [local product inventory data + specification](\ https://support.google.com/merchants/answer/3061342). + + """ + # Create or coerce a protobuf request object. + # - 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, localinventory.InsertLocalInventoryRequest): + request = localinventory.InsertLocalInventoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert_local_inventory] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_local_inventory(self, + request: Optional[Union[localinventory.DeleteLocalInventoryRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified ``LocalInventory`` from the given product + in your merchant account. It might take a up to an hour for the + ``LocalInventory`` to be deleted from the specific product. Once + you have received a successful delete response, wait for that + period before attempting a delete again. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1beta + + def sample_delete_local_inventory(): + # Create a client + client = merchant_inventories_v1beta.LocalInventoryServiceClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.DeleteLocalInventoryRequest( + name="name_value", + ) + + # Make the request + client.delete_local_inventory(request=request) + + Args: + request (Union[google.shopping.merchant_inventories_v1beta.types.DeleteLocalInventoryRequest, dict]): + The request object. Request message for the ``DeleteLocalInventory`` method. + name (str): + Required. The name of the local inventory for the given + product to delete. Format: + ``accounts/{account}/products/{product}/localInventories/{store_code}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, localinventory.DeleteLocalInventoryRequest): + request = localinventory.DeleteLocalInventoryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_local_inventory] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def __enter__(self) -> "LocalInventoryServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ( + "LocalInventoryServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/pagers.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/pagers.py new file mode 100644 index 000000000000..047973fdb67b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/pagers.py @@ -0,0 +1,166 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from 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] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.shopping.merchant_inventories_v1beta.types import localinventory + + +class ListLocalInventoriesPager: + """A pager for iterating through ``list_local_inventories`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``local_inventories`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListLocalInventories`` requests and continue to iterate + through the ``local_inventories`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesResponse` + 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[..., localinventory.ListLocalInventoriesResponse], + request: localinventory.ListLocalInventoriesRequest, + response: localinventory.ListLocalInventoriesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesRequest): + The initial request object. + response (google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = localinventory.ListLocalInventoriesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[localinventory.ListLocalInventoriesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[localinventory.LocalInventory]: + for page in self.pages: + yield from page.local_inventories + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListLocalInventoriesAsyncPager: + """A pager for iterating through ``list_local_inventories`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``local_inventories`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListLocalInventories`` requests and continue to iterate + through the ``local_inventories`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesResponse` + 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[localinventory.ListLocalInventoriesResponse]], + request: localinventory.ListLocalInventoriesRequest, + response: localinventory.ListLocalInventoriesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesRequest): + The initial request object. + response (google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = localinventory.ListLocalInventoriesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[localinventory.ListLocalInventoriesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[localinventory.LocalInventory]: + async def async_generator(): + async for page in self.pages: + for response in page.local_inventories: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/README.rst new file mode 100644 index 000000000000..816e98eb5847 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`LocalInventoryServiceTransport` is the ABC for all transports. +- public child `LocalInventoryServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `LocalInventoryServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseLocalInventoryServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `LocalInventoryServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/__init__.py new file mode 100644 index 000000000000..e1c84f7bce12 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import LocalInventoryServiceTransport +from .grpc import LocalInventoryServiceGrpcTransport +from .grpc_asyncio import LocalInventoryServiceGrpcAsyncIOTransport +from .rest import LocalInventoryServiceRestTransport +from .rest import LocalInventoryServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[LocalInventoryServiceTransport]] +_transport_registry['grpc'] = LocalInventoryServiceGrpcTransport +_transport_registry['grpc_asyncio'] = LocalInventoryServiceGrpcAsyncIOTransport +_transport_registry['rest'] = LocalInventoryServiceRestTransport + +__all__ = ( + 'LocalInventoryServiceTransport', + 'LocalInventoryServiceGrpcTransport', + 'LocalInventoryServiceGrpcAsyncIOTransport', + 'LocalInventoryServiceRestTransport', + 'LocalInventoryServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/base.py new file mode 100644 index 000000000000..df3eb9afd0a3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/base.py @@ -0,0 +1,188 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.shopping.merchant_inventories_v1beta 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 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1beta.types import localinventory + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class LocalInventoryServiceTransport(abc.ABC): + """Abstract transport class for LocalInventoryService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/content', + ) + + DEFAULT_HOST: str = 'merchantapi.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: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_local_inventories: gapic_v1.method.wrap_method( + self.list_local_inventories, + default_timeout=None, + client_info=client_info, + ), + self.insert_local_inventory: gapic_v1.method.wrap_method( + self.insert_local_inventory, + default_timeout=None, + client_info=client_info, + ), + self.delete_local_inventory: gapic_v1.method.wrap_method( + self.delete_local_inventory, + 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! + """ + raise NotImplementedError() + + @property + def list_local_inventories(self) -> Callable[ + [localinventory.ListLocalInventoriesRequest], + Union[ + localinventory.ListLocalInventoriesResponse, + Awaitable[localinventory.ListLocalInventoriesResponse] + ]]: + raise NotImplementedError() + + @property + def insert_local_inventory(self) -> Callable[ + [localinventory.InsertLocalInventoryRequest], + Union[ + localinventory.LocalInventory, + Awaitable[localinventory.LocalInventory] + ]]: + raise NotImplementedError() + + @property + def delete_local_inventory(self) -> Callable[ + [localinventory.DeleteLocalInventoryRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'LocalInventoryServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc.py new file mode 100644 index 000000000000..fd453f2f86bd --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc.py @@ -0,0 +1,418 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +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 + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1beta.types import localinventory +from .base import LocalInventoryServiceTransport, 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 + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class LocalInventoryServiceGrpcTransport(LocalInventoryServiceTransport): + """gRPC backend transport for LocalInventoryService. + + Service to manage local inventory for products + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'merchantapi.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: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'merchantapi.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. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_local_inventories(self) -> Callable[ + [localinventory.ListLocalInventoriesRequest], + localinventory.ListLocalInventoriesResponse]: + r"""Return a callable for the list local inventories method over gRPC. + + Lists the ``LocalInventory`` resources for the given product in + your merchant account. The response might contain fewer items + than specified by ``pageSize``. If ``pageToken`` was returned in + previous request, it can be used to obtain additional results. + + ``LocalInventory`` resources are listed per product for a given + account. + + Returns: + Callable[[~.ListLocalInventoriesRequest], + ~.ListLocalInventoriesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_local_inventories' not in self._stubs: + self._stubs['list_local_inventories'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1beta.LocalInventoryService/ListLocalInventories', + request_serializer=localinventory.ListLocalInventoriesRequest.serialize, + response_deserializer=localinventory.ListLocalInventoriesResponse.deserialize, + ) + return self._stubs['list_local_inventories'] + + @property + def insert_local_inventory(self) -> Callable[ + [localinventory.InsertLocalInventoryRequest], + localinventory.LocalInventory]: + r"""Return a callable for the insert local inventory method over gRPC. + + Inserts a ``LocalInventory`` resource to a product in your + merchant account. + + Replaces the full ``LocalInventory`` resource if an entry with + the same + [``storeCode``][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code] + already exists for the product. + + It might take up to 30 minutes for the new or updated + ``LocalInventory`` resource to appear in products. + + Returns: + Callable[[~.InsertLocalInventoryRequest], + ~.LocalInventory]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'insert_local_inventory' not in self._stubs: + self._stubs['insert_local_inventory'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1beta.LocalInventoryService/InsertLocalInventory', + request_serializer=localinventory.InsertLocalInventoryRequest.serialize, + response_deserializer=localinventory.LocalInventory.deserialize, + ) + return self._stubs['insert_local_inventory'] + + @property + def delete_local_inventory(self) -> Callable[ + [localinventory.DeleteLocalInventoryRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete local inventory method over gRPC. + + Deletes the specified ``LocalInventory`` from the given product + in your merchant account. It might take a up to an hour for the + ``LocalInventory`` to be deleted from the specific product. Once + you have received a successful delete response, wait for that + period before attempting a delete again. + + Returns: + Callable[[~.DeleteLocalInventoryRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_local_inventory' not in self._stubs: + self._stubs['delete_local_inventory'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1beta.LocalInventoryService/DeleteLocalInventory', + request_serializer=localinventory.DeleteLocalInventoryRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_local_inventory'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'LocalInventoryServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..8e11b62a9522 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc_asyncio.py @@ -0,0 +1,449 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import pickle +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 retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.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.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1beta.types import localinventory +from .base import LocalInventoryServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import LocalInventoryServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class LocalInventoryServiceGrpcAsyncIOTransport(LocalInventoryServiceTransport): + """gRPC AsyncIO backend transport for LocalInventoryService. + + Service to manage local inventory for products + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'merchantapi.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. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'merchantapi.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: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_local_inventories(self) -> Callable[ + [localinventory.ListLocalInventoriesRequest], + Awaitable[localinventory.ListLocalInventoriesResponse]]: + r"""Return a callable for the list local inventories method over gRPC. + + Lists the ``LocalInventory`` resources for the given product in + your merchant account. The response might contain fewer items + than specified by ``pageSize``. If ``pageToken`` was returned in + previous request, it can be used to obtain additional results. + + ``LocalInventory`` resources are listed per product for a given + account. + + Returns: + Callable[[~.ListLocalInventoriesRequest], + Awaitable[~.ListLocalInventoriesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_local_inventories' not in self._stubs: + self._stubs['list_local_inventories'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1beta.LocalInventoryService/ListLocalInventories', + request_serializer=localinventory.ListLocalInventoriesRequest.serialize, + response_deserializer=localinventory.ListLocalInventoriesResponse.deserialize, + ) + return self._stubs['list_local_inventories'] + + @property + def insert_local_inventory(self) -> Callable[ + [localinventory.InsertLocalInventoryRequest], + Awaitable[localinventory.LocalInventory]]: + r"""Return a callable for the insert local inventory method over gRPC. + + Inserts a ``LocalInventory`` resource to a product in your + merchant account. + + Replaces the full ``LocalInventory`` resource if an entry with + the same + [``storeCode``][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code] + already exists for the product. + + It might take up to 30 minutes for the new or updated + ``LocalInventory`` resource to appear in products. + + Returns: + Callable[[~.InsertLocalInventoryRequest], + Awaitable[~.LocalInventory]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'insert_local_inventory' not in self._stubs: + self._stubs['insert_local_inventory'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1beta.LocalInventoryService/InsertLocalInventory', + request_serializer=localinventory.InsertLocalInventoryRequest.serialize, + response_deserializer=localinventory.LocalInventory.deserialize, + ) + return self._stubs['insert_local_inventory'] + + @property + def delete_local_inventory(self) -> Callable[ + [localinventory.DeleteLocalInventoryRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete local inventory method over gRPC. + + Deletes the specified ``LocalInventory`` from the given product + in your merchant account. It might take a up to an hour for the + ``LocalInventory`` to be deleted from the specific product. Once + you have received a successful delete response, wait for that + period before attempting a delete again. + + Returns: + Callable[[~.DeleteLocalInventoryRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_local_inventory' not in self._stubs: + self._stubs['delete_local_inventory'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1beta.LocalInventoryService/DeleteLocalInventory', + request_serializer=localinventory.DeleteLocalInventoryRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_local_inventory'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_local_inventories: self._wrap_method( + self.list_local_inventories, + default_timeout=None, + client_info=client_info, + ), + self.insert_local_inventory: self._wrap_method( + self.insert_local_inventory, + default_timeout=None, + client_info=client_info, + ), + self.delete_local_inventory: self._wrap_method( + self.delete_local_inventory, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + +__all__ = ( + 'LocalInventoryServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest.py new file mode 100644 index 000000000000..651ae59e98d5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest.py @@ -0,0 +1,640 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import 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 warnings + + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1beta.types import localinventory + + +from .rest_base import _BaseLocalInventoryServiceRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class LocalInventoryServiceRestInterceptor: + """Interceptor for LocalInventoryService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the LocalInventoryServiceRestTransport. + + .. code-block:: python + class MyCustomLocalInventoryServiceInterceptor(LocalInventoryServiceRestInterceptor): + def pre_delete_local_inventory(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_insert_local_inventory(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_insert_local_inventory(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_local_inventories(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_local_inventories(self, response): + logging.log(f"Received response: {response}") + return response + + transport = LocalInventoryServiceRestTransport(interceptor=MyCustomLocalInventoryServiceInterceptor()) + client = LocalInventoryServiceClient(transport=transport) + + + """ + def pre_delete_local_inventory(self, request: localinventory.DeleteLocalInventoryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[localinventory.DeleteLocalInventoryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_local_inventory + + Override in a subclass to manipulate the request or metadata + before they are sent to the LocalInventoryService server. + """ + return request, metadata + + def pre_insert_local_inventory(self, request: localinventory.InsertLocalInventoryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[localinventory.InsertLocalInventoryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for insert_local_inventory + + Override in a subclass to manipulate the request or metadata + before they are sent to the LocalInventoryService server. + """ + return request, metadata + + def post_insert_local_inventory(self, response: localinventory.LocalInventory) -> localinventory.LocalInventory: + """Post-rpc interceptor for insert_local_inventory + + DEPRECATED. Please use the `post_insert_local_inventory_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the LocalInventoryService server but before + it is returned to user code. This `post_insert_local_inventory` interceptor runs + before the `post_insert_local_inventory_with_metadata` interceptor. + """ + return response + + def post_insert_local_inventory_with_metadata(self, response: localinventory.LocalInventory, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[localinventory.LocalInventory, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for insert_local_inventory + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the LocalInventoryService server but before it is returned to user code. + + We recommend only using this `post_insert_local_inventory_with_metadata` + interceptor in new development instead of the `post_insert_local_inventory` interceptor. + When both interceptors are used, this `post_insert_local_inventory_with_metadata` interceptor runs after the + `post_insert_local_inventory` interceptor. The (possibly modified) response returned by + `post_insert_local_inventory` will be passed to + `post_insert_local_inventory_with_metadata`. + """ + return response, metadata + + def pre_list_local_inventories(self, request: localinventory.ListLocalInventoriesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[localinventory.ListLocalInventoriesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_local_inventories + + Override in a subclass to manipulate the request or metadata + before they are sent to the LocalInventoryService server. + """ + return request, metadata + + def post_list_local_inventories(self, response: localinventory.ListLocalInventoriesResponse) -> localinventory.ListLocalInventoriesResponse: + """Post-rpc interceptor for list_local_inventories + + DEPRECATED. Please use the `post_list_local_inventories_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the LocalInventoryService server but before + it is returned to user code. This `post_list_local_inventories` interceptor runs + before the `post_list_local_inventories_with_metadata` interceptor. + """ + return response + + def post_list_local_inventories_with_metadata(self, response: localinventory.ListLocalInventoriesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[localinventory.ListLocalInventoriesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_local_inventories + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the LocalInventoryService server but before it is returned to user code. + + We recommend only using this `post_list_local_inventories_with_metadata` + interceptor in new development instead of the `post_list_local_inventories` interceptor. + When both interceptors are used, this `post_list_local_inventories_with_metadata` interceptor runs after the + `post_list_local_inventories` interceptor. The (possibly modified) response returned by + `post_list_local_inventories` will be passed to + `post_list_local_inventories_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class LocalInventoryServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: LocalInventoryServiceRestInterceptor + + +class LocalInventoryServiceRestTransport(_BaseLocalInventoryServiceRestTransport): + """REST backend synchronous transport for LocalInventoryService. + + Service to manage local inventory for products + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'merchantapi.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[LocalInventoryServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or LocalInventoryServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _DeleteLocalInventory(_BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory, LocalInventoryServiceRestStub): + def __hash__(self): + return hash("LocalInventoryServiceRestTransport.DeleteLocalInventory") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: localinventory.DeleteLocalInventoryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete local inventory method over HTTP. + + Args: + request (~.localinventory.DeleteLocalInventoryRequest): + The request object. Request message for the ``DeleteLocalInventory`` 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 = _BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._get_http_options() + + request, metadata = self._interceptor.pre_delete_local_inventory(request, metadata) + transcoded_request = _BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient.DeleteLocalInventory", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "rpcName": "DeleteLocalInventory", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LocalInventoryServiceRestTransport._DeleteLocalInventory._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 _InsertLocalInventory(_BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory, LocalInventoryServiceRestStub): + def __hash__(self): + return hash("LocalInventoryServiceRestTransport.InsertLocalInventory") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: localinventory.InsertLocalInventoryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> localinventory.LocalInventory: + r"""Call the insert local inventory method over HTTP. + + Args: + request (~.localinventory.InsertLocalInventoryRequest): + The request object. Request message for the ``InsertLocalInventory`` 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: + ~.localinventory.LocalInventory: + Local inventory information for the product. Represents + in-store information for a specific product at the store + specified by + [``storeCode``][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code]. + For a list of all accepted attribute values, see the + `local product inventory data + specification `__. + + """ + + http_options = _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_http_options() + + request, metadata = self._interceptor.pre_insert_local_inventory(request, metadata) + transcoded_request = _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_transcoded_request(http_options, request) + + body = _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient.InsertLocalInventory", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "rpcName": "InsertLocalInventory", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LocalInventoryServiceRestTransport._InsertLocalInventory._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = localinventory.LocalInventory() + pb_resp = localinventory.LocalInventory.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_insert_local_inventory(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_insert_local_inventory_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = localinventory.LocalInventory.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient.insert_local_inventory", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "rpcName": "InsertLocalInventory", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListLocalInventories(_BaseLocalInventoryServiceRestTransport._BaseListLocalInventories, LocalInventoryServiceRestStub): + def __hash__(self): + return hash("LocalInventoryServiceRestTransport.ListLocalInventories") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: localinventory.ListLocalInventoriesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> localinventory.ListLocalInventoriesResponse: + r"""Call the list local inventories method over HTTP. + + Args: + request (~.localinventory.ListLocalInventoriesRequest): + The request object. Request message for the ``ListLocalInventories`` 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: + ~.localinventory.ListLocalInventoriesResponse: + Response message for the ``ListLocalInventories`` + method. + + """ + + http_options = _BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._get_http_options() + + request, metadata = self._interceptor.pre_list_local_inventories(request, metadata) + transcoded_request = _BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient.ListLocalInventories", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "rpcName": "ListLocalInventories", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LocalInventoryServiceRestTransport._ListLocalInventories._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = localinventory.ListLocalInventoriesResponse() + pb_resp = localinventory.ListLocalInventoriesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_local_inventories(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_local_inventories_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = localinventory.ListLocalInventoriesResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient.list_local_inventories", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "rpcName": "ListLocalInventories", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def delete_local_inventory(self) -> Callable[ + [localinventory.DeleteLocalInventoryRequest], + 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._DeleteLocalInventory(self._session, self._host, self._interceptor) # type: ignore + + @property + def insert_local_inventory(self) -> Callable[ + [localinventory.InsertLocalInventoryRequest], + localinventory.LocalInventory]: + # 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._InsertLocalInventory(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_local_inventories(self) -> Callable[ + [localinventory.ListLocalInventoriesRequest], + localinventory.ListLocalInventoriesResponse]: + # 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._ListLocalInventories(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'LocalInventoryServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest_base.py new file mode 100644 index 000000000000..0394bb42ce48 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest_base.py @@ -0,0 +1,213 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from .base import LocalInventoryServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1beta.types import localinventory + + +class _BaseLocalInventoryServiceRestTransport(LocalInventoryServiceTransport): + """Base REST backend transport for LocalInventoryService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'merchantapi.googleapis.com', + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + + class _BaseDeleteLocalInventory: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/inventories/v1beta/{name=accounts/*/products/*/localInventories/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = localinventory.DeleteLocalInventoryRequest.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(_BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseInsertLocalInventory: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/inventories/v1beta/{parent=accounts/*/products/*}/localInventories:insert', + 'body': 'local_inventory', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = localinventory.InsertLocalInventoryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListLocalInventories: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/inventories/v1beta/{parent=accounts/*/products/*}/localInventories', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = localinventory.ListLocalInventoriesRequest.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(_BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseLocalInventoryServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/__init__.py new file mode 100644 index 000000000000..1a0839e5cff5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import RegionalInventoryServiceClient +from .async_client import RegionalInventoryServiceAsyncClient + +__all__ = ( + 'RegionalInventoryServiceClient', + 'RegionalInventoryServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/async_client.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/async_client.py new file mode 100644 index 000000000000..e041a2099942 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/async_client.py @@ -0,0 +1,597 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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.shopping.merchant_inventories_v1beta 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.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + + +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.shopping.merchant_inventories_v1beta.services.regional_inventory_service import pagers +from google.shopping.merchant_inventories_v1beta.types import regionalinventory +from google.shopping.type.types import types +from google.type import interval_pb2 # type: ignore +from .transports.base import RegionalInventoryServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import RegionalInventoryServiceGrpcAsyncIOTransport +from .client import RegionalInventoryServiceClient + +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 RegionalInventoryServiceAsyncClient: + """Service to manage regional inventory for products. There is also + separate ``regions`` resource and API to manage regions definitions. + """ + + _client: RegionalInventoryServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = RegionalInventoryServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = RegionalInventoryServiceClient._DEFAULT_UNIVERSE + + regional_inventory_path = staticmethod(RegionalInventoryServiceClient.regional_inventory_path) + parse_regional_inventory_path = staticmethod(RegionalInventoryServiceClient.parse_regional_inventory_path) + common_billing_account_path = staticmethod(RegionalInventoryServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(RegionalInventoryServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(RegionalInventoryServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(RegionalInventoryServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(RegionalInventoryServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(RegionalInventoryServiceClient.parse_common_organization_path) + common_project_path = staticmethod(RegionalInventoryServiceClient.common_project_path) + parse_common_project_path = staticmethod(RegionalInventoryServiceClient.parse_common_project_path) + common_location_path = staticmethod(RegionalInventoryServiceClient.common_location_path) + parse_common_location_path = staticmethod(RegionalInventoryServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RegionalInventoryServiceAsyncClient: The constructed client. + """ + return RegionalInventoryServiceClient.from_service_account_info.__func__(RegionalInventoryServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RegionalInventoryServiceAsyncClient: The constructed client. + """ + return RegionalInventoryServiceClient.from_service_account_file.__func__(RegionalInventoryServiceAsyncClient, 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): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return RegionalInventoryServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> RegionalInventoryServiceTransport: + """Returns the transport used by the client instance. + + Returns: + RegionalInventoryServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = RegionalInventoryServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, RegionalInventoryServiceTransport, Callable[..., RegionalInventoryServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the regional inventory service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,RegionalInventoryServiceTransport,Callable[..., RegionalInventoryServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the RegionalInventoryServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = RegionalInventoryServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._client._transport, "_credentials") else { + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "credentialsType": None, + } + ) + + async def list_regional_inventories(self, + request: Optional[Union[regionalinventory.ListRegionalInventoriesRequest, 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.ListRegionalInventoriesAsyncPager: + r"""Lists the ``RegionalInventory`` resources for the given product + in your merchant account. The response might contain fewer items + than specified by ``pageSize``. If ``pageToken`` was returned in + previous request, it can be used to obtain additional results. + + ``RegionalInventory`` resources are listed per product for a + given account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1beta + + async def sample_list_regional_inventories(): + # Create a client + client = merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.ListRegionalInventoriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_regional_inventories(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesRequest, dict]]): + The request object. Request message for the ``ListRegionalInventories`` + method. + parent (:class:`str`): + Required. The ``name`` of the parent product to list + ``RegionalInventory`` resources for. Format: + ``accounts/{account}/products/{product}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.pagers.ListRegionalInventoriesAsyncPager: + Response message for the ListRegionalInventories method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, regionalinventory.ListRegionalInventoriesRequest): + request = regionalinventory.ListRegionalInventoriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_regional_inventories] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListRegionalInventoriesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def insert_regional_inventory(self, + request: Optional[Union[regionalinventory.InsertRegionalInventoryRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regionalinventory.RegionalInventory: + r"""Inserts a ``RegionalInventory`` to a given product in your + merchant account. + + Replaces the full ``RegionalInventory`` resource if an entry + with the same + [``region``][google.shopping.merchant.inventories.v1beta.RegionalInventory.region] + already exists for the product. + + It might take up to 30 minutes for the new or updated + ``RegionalInventory`` resource to appear in products. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1beta + + async def sample_insert_regional_inventory(): + # Create a client + client = merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient() + + # Initialize request argument(s) + regional_inventory = merchant_inventories_v1beta.RegionalInventory() + regional_inventory.region = "region_value" + + request = merchant_inventories_v1beta.InsertRegionalInventoryRequest( + parent="parent_value", + regional_inventory=regional_inventory, + ) + + # Make the request + response = await client.insert_regional_inventory(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_inventories_v1beta.types.InsertRegionalInventoryRequest, dict]]): + The request object. Request message for the ``InsertRegionalInventory`` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.shopping.merchant_inventories_v1beta.types.RegionalInventory: + Regional inventory information for the product. Represents specific + information like price and availability for a given + product in a specific + [region][google.shopping.merchant.inventories.v1beta.RegionalInventory.region]. + For a list of all accepted attribute values, see the + [regional product inventory data + specification](\ https://support.google.com/merchants/answer/9698880). + + """ + # Create or coerce a protobuf request object. + # - 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, regionalinventory.InsertRegionalInventoryRequest): + request = regionalinventory.InsertRegionalInventoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.insert_regional_inventory] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_regional_inventory(self, + request: Optional[Union[regionalinventory.DeleteRegionalInventoryRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified ``RegionalInventory`` resource from the + given product in your merchant account. It might take up to an + hour for the ``RegionalInventory`` to be deleted from the + specific product. Once you have received a successful delete + response, wait for that period before attempting a delete again. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1beta + + async def sample_delete_regional_inventory(): + # Create a client + client = merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.DeleteRegionalInventoryRequest( + name="name_value", + ) + + # Make the request + await client.delete_regional_inventory(request=request) + + Args: + request (Optional[Union[google.shopping.merchant_inventories_v1beta.types.DeleteRegionalInventoryRequest, dict]]): + The request object. Request message for the ``DeleteRegionalInventory`` + method. + name (:class:`str`): + Required. The name of the ``RegionalInventory`` resource + to delete. Format: + ``accounts/{account}/products/{product}/regionalInventories/{region}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, regionalinventory.DeleteRegionalInventoryRequest): + request = regionalinventory.DeleteRegionalInventoryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_regional_inventory] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self) -> "RegionalInventoryServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ( + "RegionalInventoryServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/client.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/client.py new file mode 100644 index 000000000000..467abad899d0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/client.py @@ -0,0 +1,956 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.shopping.merchant_inventories_v1beta 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.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 + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service import pagers +from google.shopping.merchant_inventories_v1beta.types import regionalinventory +from google.shopping.type.types import types +from google.type import interval_pb2 # type: ignore +from .transports.base import RegionalInventoryServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import RegionalInventoryServiceGrpcTransport +from .transports.grpc_asyncio import RegionalInventoryServiceGrpcAsyncIOTransport +from .transports.rest import RegionalInventoryServiceRestTransport + + +class RegionalInventoryServiceClientMeta(type): + """Metaclass for the RegionalInventoryService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[RegionalInventoryServiceTransport]] + _transport_registry["grpc"] = RegionalInventoryServiceGrpcTransport + _transport_registry["grpc_asyncio"] = RegionalInventoryServiceGrpcAsyncIOTransport + _transport_registry["rest"] = RegionalInventoryServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[RegionalInventoryServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class RegionalInventoryServiceClient(metaclass=RegionalInventoryServiceClientMeta): + """Service to manage regional inventory for products. There is also + separate ``regions`` resource and API to manage regions definitions. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "merchantapi.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "merchantapi.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RegionalInventoryServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RegionalInventoryServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> RegionalInventoryServiceTransport: + """Returns the transport used by the client instance. + + Returns: + RegionalInventoryServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def regional_inventory_path(account: str,product: str,region: str,) -> str: + """Returns a fully-qualified regional_inventory string.""" + return "accounts/{account}/products/{product}/regionalInventories/{region}".format(account=account, product=product, region=region, ) + + @staticmethod + def parse_regional_inventory_path(path: str) -> Dict[str,str]: + """Parses a regional_inventory path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/products/(?P.+?)/regionalInventories/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + 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: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + 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) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "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 + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_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): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = RegionalInventoryServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = RegionalInventoryServiceClient._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: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = RegionalInventoryServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + 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]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, RegionalInventoryServiceTransport, Callable[..., RegionalInventoryServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the regional inventory service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,RegionalInventoryServiceTransport,Callable[..., RegionalInventoryServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the RegionalInventoryServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + 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) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = RegionalInventoryServiceClient._read_environment_variables() + self._client_cert_source = RegionalInventoryServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = RegionalInventoryServiceClient._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 + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + 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") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, RegionalInventoryServiceTransport) + if transport_provided: + # transport is a RegionalInventoryServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + 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." + ) + self._transport = cast(RegionalInventoryServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + RegionalInventoryServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + 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) + + transport_init: Union[Type[RegionalInventoryServiceTransport], Callable[..., RegionalInventoryServiceTransport]] = ( + RegionalInventoryServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., RegionalInventoryServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "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 { + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "credentialsType": None, + } + ) + + def list_regional_inventories(self, + request: Optional[Union[regionalinventory.ListRegionalInventoriesRequest, 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.ListRegionalInventoriesPager: + r"""Lists the ``RegionalInventory`` resources for the given product + in your merchant account. The response might contain fewer items + than specified by ``pageSize``. If ``pageToken`` was returned in + previous request, it can be used to obtain additional results. + + ``RegionalInventory`` resources are listed per product for a + given account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1beta + + def sample_list_regional_inventories(): + # Create a client + client = merchant_inventories_v1beta.RegionalInventoryServiceClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.ListRegionalInventoriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_regional_inventories(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesRequest, dict]): + The request object. Request message for the ``ListRegionalInventories`` + method. + parent (str): + Required. The ``name`` of the parent product to list + ``RegionalInventory`` resources for. Format: + ``accounts/{account}/products/{product}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.pagers.ListRegionalInventoriesPager: + Response message for the ListRegionalInventories method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, regionalinventory.ListRegionalInventoriesRequest): + request = regionalinventory.ListRegionalInventoriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_regional_inventories] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListRegionalInventoriesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def insert_regional_inventory(self, + request: Optional[Union[regionalinventory.InsertRegionalInventoryRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regionalinventory.RegionalInventory: + r"""Inserts a ``RegionalInventory`` to a given product in your + merchant account. + + Replaces the full ``RegionalInventory`` resource if an entry + with the same + [``region``][google.shopping.merchant.inventories.v1beta.RegionalInventory.region] + already exists for the product. + + It might take up to 30 minutes for the new or updated + ``RegionalInventory`` resource to appear in products. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1beta + + def sample_insert_regional_inventory(): + # Create a client + client = merchant_inventories_v1beta.RegionalInventoryServiceClient() + + # Initialize request argument(s) + regional_inventory = merchant_inventories_v1beta.RegionalInventory() + regional_inventory.region = "region_value" + + request = merchant_inventories_v1beta.InsertRegionalInventoryRequest( + parent="parent_value", + regional_inventory=regional_inventory, + ) + + # Make the request + response = client.insert_regional_inventory(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_inventories_v1beta.types.InsertRegionalInventoryRequest, dict]): + The request object. Request message for the ``InsertRegionalInventory`` + 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: + google.shopping.merchant_inventories_v1beta.types.RegionalInventory: + Regional inventory information for the product. Represents specific + information like price and availability for a given + product in a specific + [region][google.shopping.merchant.inventories.v1beta.RegionalInventory.region]. + For a list of all accepted attribute values, see the + [regional product inventory data + specification](\ https://support.google.com/merchants/answer/9698880). + + """ + # Create or coerce a protobuf request object. + # - 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, regionalinventory.InsertRegionalInventoryRequest): + request = regionalinventory.InsertRegionalInventoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert_regional_inventory] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_regional_inventory(self, + request: Optional[Union[regionalinventory.DeleteRegionalInventoryRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified ``RegionalInventory`` resource from the + given product in your merchant account. It might take up to an + hour for the ``RegionalInventory`` to be deleted from the + specific product. Once you have received a successful delete + response, wait for that period before attempting a delete again. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.shopping import merchant_inventories_v1beta + + def sample_delete_regional_inventory(): + # Create a client + client = merchant_inventories_v1beta.RegionalInventoryServiceClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.DeleteRegionalInventoryRequest( + name="name_value", + ) + + # Make the request + client.delete_regional_inventory(request=request) + + Args: + request (Union[google.shopping.merchant_inventories_v1beta.types.DeleteRegionalInventoryRequest, dict]): + The request object. Request message for the ``DeleteRegionalInventory`` + method. + name (str): + Required. The name of the ``RegionalInventory`` resource + to delete. Format: + ``accounts/{account}/products/{product}/regionalInventories/{region}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, regionalinventory.DeleteRegionalInventoryRequest): + request = regionalinventory.DeleteRegionalInventoryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_regional_inventory] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def __enter__(self) -> "RegionalInventoryServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ( + "RegionalInventoryServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/pagers.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/pagers.py new file mode 100644 index 000000000000..ba0ad8732af1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/pagers.py @@ -0,0 +1,166 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from 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] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.shopping.merchant_inventories_v1beta.types import regionalinventory + + +class ListRegionalInventoriesPager: + """A pager for iterating through ``list_regional_inventories`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``regional_inventories`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListRegionalInventories`` requests and continue to iterate + through the ``regional_inventories`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesResponse` + 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[..., regionalinventory.ListRegionalInventoriesResponse], + request: regionalinventory.ListRegionalInventoriesRequest, + response: regionalinventory.ListRegionalInventoriesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesRequest): + The initial request object. + response (google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = regionalinventory.ListRegionalInventoriesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[regionalinventory.ListRegionalInventoriesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[regionalinventory.RegionalInventory]: + for page in self.pages: + yield from page.regional_inventories + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListRegionalInventoriesAsyncPager: + """A pager for iterating through ``list_regional_inventories`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``regional_inventories`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListRegionalInventories`` requests and continue to iterate + through the ``regional_inventories`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesResponse` + 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[regionalinventory.ListRegionalInventoriesResponse]], + request: regionalinventory.ListRegionalInventoriesRequest, + response: regionalinventory.ListRegionalInventoriesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesRequest): + The initial request object. + response (google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = regionalinventory.ListRegionalInventoriesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[regionalinventory.ListRegionalInventoriesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[regionalinventory.RegionalInventory]: + async def async_generator(): + async for page in self.pages: + for response in page.regional_inventories: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/README.rst new file mode 100644 index 000000000000..0b66f48dbd0c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`RegionalInventoryServiceTransport` is the ABC for all transports. +- public child `RegionalInventoryServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `RegionalInventoryServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseRegionalInventoryServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `RegionalInventoryServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/__init__.py new file mode 100644 index 000000000000..b26a37767f11 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import RegionalInventoryServiceTransport +from .grpc import RegionalInventoryServiceGrpcTransport +from .grpc_asyncio import RegionalInventoryServiceGrpcAsyncIOTransport +from .rest import RegionalInventoryServiceRestTransport +from .rest import RegionalInventoryServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[RegionalInventoryServiceTransport]] +_transport_registry['grpc'] = RegionalInventoryServiceGrpcTransport +_transport_registry['grpc_asyncio'] = RegionalInventoryServiceGrpcAsyncIOTransport +_transport_registry['rest'] = RegionalInventoryServiceRestTransport + +__all__ = ( + 'RegionalInventoryServiceTransport', + 'RegionalInventoryServiceGrpcTransport', + 'RegionalInventoryServiceGrpcAsyncIOTransport', + 'RegionalInventoryServiceRestTransport', + 'RegionalInventoryServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/base.py new file mode 100644 index 000000000000..8980c90b8cae --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/base.py @@ -0,0 +1,188 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.shopping.merchant_inventories_v1beta 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 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1beta.types import regionalinventory + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class RegionalInventoryServiceTransport(abc.ABC): + """Abstract transport class for RegionalInventoryService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/content', + ) + + DEFAULT_HOST: str = 'merchantapi.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: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_regional_inventories: gapic_v1.method.wrap_method( + self.list_regional_inventories, + default_timeout=None, + client_info=client_info, + ), + self.insert_regional_inventory: gapic_v1.method.wrap_method( + self.insert_regional_inventory, + default_timeout=None, + client_info=client_info, + ), + self.delete_regional_inventory: gapic_v1.method.wrap_method( + self.delete_regional_inventory, + 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! + """ + raise NotImplementedError() + + @property + def list_regional_inventories(self) -> Callable[ + [regionalinventory.ListRegionalInventoriesRequest], + Union[ + regionalinventory.ListRegionalInventoriesResponse, + Awaitable[regionalinventory.ListRegionalInventoriesResponse] + ]]: + raise NotImplementedError() + + @property + def insert_regional_inventory(self) -> Callable[ + [regionalinventory.InsertRegionalInventoryRequest], + Union[ + regionalinventory.RegionalInventory, + Awaitable[regionalinventory.RegionalInventory] + ]]: + raise NotImplementedError() + + @property + def delete_regional_inventory(self) -> Callable[ + [regionalinventory.DeleteRegionalInventoryRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'RegionalInventoryServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc.py new file mode 100644 index 000000000000..ed62b0394def --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc.py @@ -0,0 +1,419 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +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 + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1beta.types import regionalinventory +from .base import RegionalInventoryServiceTransport, 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 + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class RegionalInventoryServiceGrpcTransport(RegionalInventoryServiceTransport): + """gRPC backend transport for RegionalInventoryService. + + Service to manage regional inventory for products. There is also + separate ``regions`` resource and API to manage regions definitions. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'merchantapi.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: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'merchantapi.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. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_regional_inventories(self) -> Callable[ + [regionalinventory.ListRegionalInventoriesRequest], + regionalinventory.ListRegionalInventoriesResponse]: + r"""Return a callable for the list regional inventories method over gRPC. + + Lists the ``RegionalInventory`` resources for the given product + in your merchant account. The response might contain fewer items + than specified by ``pageSize``. If ``pageToken`` was returned in + previous request, it can be used to obtain additional results. + + ``RegionalInventory`` resources are listed per product for a + given account. + + Returns: + Callable[[~.ListRegionalInventoriesRequest], + ~.ListRegionalInventoriesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_regional_inventories' not in self._stubs: + self._stubs['list_regional_inventories'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/ListRegionalInventories', + request_serializer=regionalinventory.ListRegionalInventoriesRequest.serialize, + response_deserializer=regionalinventory.ListRegionalInventoriesResponse.deserialize, + ) + return self._stubs['list_regional_inventories'] + + @property + def insert_regional_inventory(self) -> Callable[ + [regionalinventory.InsertRegionalInventoryRequest], + regionalinventory.RegionalInventory]: + r"""Return a callable for the insert regional inventory method over gRPC. + + Inserts a ``RegionalInventory`` to a given product in your + merchant account. + + Replaces the full ``RegionalInventory`` resource if an entry + with the same + [``region``][google.shopping.merchant.inventories.v1beta.RegionalInventory.region] + already exists for the product. + + It might take up to 30 minutes for the new or updated + ``RegionalInventory`` resource to appear in products. + + Returns: + Callable[[~.InsertRegionalInventoryRequest], + ~.RegionalInventory]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'insert_regional_inventory' not in self._stubs: + self._stubs['insert_regional_inventory'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/InsertRegionalInventory', + request_serializer=regionalinventory.InsertRegionalInventoryRequest.serialize, + response_deserializer=regionalinventory.RegionalInventory.deserialize, + ) + return self._stubs['insert_regional_inventory'] + + @property + def delete_regional_inventory(self) -> Callable[ + [regionalinventory.DeleteRegionalInventoryRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete regional inventory method over gRPC. + + Deletes the specified ``RegionalInventory`` resource from the + given product in your merchant account. It might take up to an + hour for the ``RegionalInventory`` to be deleted from the + specific product. Once you have received a successful delete + response, wait for that period before attempting a delete again. + + Returns: + Callable[[~.DeleteRegionalInventoryRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_regional_inventory' not in self._stubs: + self._stubs['delete_regional_inventory'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/DeleteRegionalInventory', + request_serializer=regionalinventory.DeleteRegionalInventoryRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_regional_inventory'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'RegionalInventoryServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..e444d0268208 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc_asyncio.py @@ -0,0 +1,450 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import pickle +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 retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.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.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1beta.types import regionalinventory +from .base import RegionalInventoryServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import RegionalInventoryServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class RegionalInventoryServiceGrpcAsyncIOTransport(RegionalInventoryServiceTransport): + """gRPC AsyncIO backend transport for RegionalInventoryService. + + Service to manage regional inventory for products. There is also + separate ``regions`` resource and API to manage regions definitions. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'merchantapi.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. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'merchantapi.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: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_regional_inventories(self) -> Callable[ + [regionalinventory.ListRegionalInventoriesRequest], + Awaitable[regionalinventory.ListRegionalInventoriesResponse]]: + r"""Return a callable for the list regional inventories method over gRPC. + + Lists the ``RegionalInventory`` resources for the given product + in your merchant account. The response might contain fewer items + than specified by ``pageSize``. If ``pageToken`` was returned in + previous request, it can be used to obtain additional results. + + ``RegionalInventory`` resources are listed per product for a + given account. + + Returns: + Callable[[~.ListRegionalInventoriesRequest], + Awaitable[~.ListRegionalInventoriesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_regional_inventories' not in self._stubs: + self._stubs['list_regional_inventories'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/ListRegionalInventories', + request_serializer=regionalinventory.ListRegionalInventoriesRequest.serialize, + response_deserializer=regionalinventory.ListRegionalInventoriesResponse.deserialize, + ) + return self._stubs['list_regional_inventories'] + + @property + def insert_regional_inventory(self) -> Callable[ + [regionalinventory.InsertRegionalInventoryRequest], + Awaitable[regionalinventory.RegionalInventory]]: + r"""Return a callable for the insert regional inventory method over gRPC. + + Inserts a ``RegionalInventory`` to a given product in your + merchant account. + + Replaces the full ``RegionalInventory`` resource if an entry + with the same + [``region``][google.shopping.merchant.inventories.v1beta.RegionalInventory.region] + already exists for the product. + + It might take up to 30 minutes for the new or updated + ``RegionalInventory`` resource to appear in products. + + Returns: + Callable[[~.InsertRegionalInventoryRequest], + Awaitable[~.RegionalInventory]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'insert_regional_inventory' not in self._stubs: + self._stubs['insert_regional_inventory'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/InsertRegionalInventory', + request_serializer=regionalinventory.InsertRegionalInventoryRequest.serialize, + response_deserializer=regionalinventory.RegionalInventory.deserialize, + ) + return self._stubs['insert_regional_inventory'] + + @property + def delete_regional_inventory(self) -> Callable[ + [regionalinventory.DeleteRegionalInventoryRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete regional inventory method over gRPC. + + Deletes the specified ``RegionalInventory`` resource from the + given product in your merchant account. It might take up to an + hour for the ``RegionalInventory`` to be deleted from the + specific product. Once you have received a successful delete + response, wait for that period before attempting a delete again. + + Returns: + Callable[[~.DeleteRegionalInventoryRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_regional_inventory' not in self._stubs: + self._stubs['delete_regional_inventory'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/DeleteRegionalInventory', + request_serializer=regionalinventory.DeleteRegionalInventoryRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_regional_inventory'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_regional_inventories: self._wrap_method( + self.list_regional_inventories, + default_timeout=None, + client_info=client_info, + ), + self.insert_regional_inventory: self._wrap_method( + self.insert_regional_inventory, + default_timeout=None, + client_info=client_info, + ), + self.delete_regional_inventory: self._wrap_method( + self.delete_regional_inventory, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + +__all__ = ( + 'RegionalInventoryServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest.py new file mode 100644 index 000000000000..3991d4beb736 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest.py @@ -0,0 +1,644 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import 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 warnings + + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1beta.types import regionalinventory + + +from .rest_base import _BaseRegionalInventoryServiceRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class RegionalInventoryServiceRestInterceptor: + """Interceptor for RegionalInventoryService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the RegionalInventoryServiceRestTransport. + + .. code-block:: python + class MyCustomRegionalInventoryServiceInterceptor(RegionalInventoryServiceRestInterceptor): + def pre_delete_regional_inventory(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_insert_regional_inventory(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_insert_regional_inventory(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_regional_inventories(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_regional_inventories(self, response): + logging.log(f"Received response: {response}") + return response + + transport = RegionalInventoryServiceRestTransport(interceptor=MyCustomRegionalInventoryServiceInterceptor()) + client = RegionalInventoryServiceClient(transport=transport) + + + """ + def pre_delete_regional_inventory(self, request: regionalinventory.DeleteRegionalInventoryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regionalinventory.DeleteRegionalInventoryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_regional_inventory + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionalInventoryService server. + """ + return request, metadata + + def pre_insert_regional_inventory(self, request: regionalinventory.InsertRegionalInventoryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regionalinventory.InsertRegionalInventoryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for insert_regional_inventory + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionalInventoryService server. + """ + return request, metadata + + def post_insert_regional_inventory(self, response: regionalinventory.RegionalInventory) -> regionalinventory.RegionalInventory: + """Post-rpc interceptor for insert_regional_inventory + + DEPRECATED. Please use the `post_insert_regional_inventory_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the RegionalInventoryService server but before + it is returned to user code. This `post_insert_regional_inventory` interceptor runs + before the `post_insert_regional_inventory_with_metadata` interceptor. + """ + return response + + def post_insert_regional_inventory_with_metadata(self, response: regionalinventory.RegionalInventory, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regionalinventory.RegionalInventory, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for insert_regional_inventory + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the RegionalInventoryService server but before it is returned to user code. + + We recommend only using this `post_insert_regional_inventory_with_metadata` + interceptor in new development instead of the `post_insert_regional_inventory` interceptor. + When both interceptors are used, this `post_insert_regional_inventory_with_metadata` interceptor runs after the + `post_insert_regional_inventory` interceptor. The (possibly modified) response returned by + `post_insert_regional_inventory` will be passed to + `post_insert_regional_inventory_with_metadata`. + """ + return response, metadata + + def pre_list_regional_inventories(self, request: regionalinventory.ListRegionalInventoriesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regionalinventory.ListRegionalInventoriesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_regional_inventories + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionalInventoryService server. + """ + return request, metadata + + def post_list_regional_inventories(self, response: regionalinventory.ListRegionalInventoriesResponse) -> regionalinventory.ListRegionalInventoriesResponse: + """Post-rpc interceptor for list_regional_inventories + + DEPRECATED. Please use the `post_list_regional_inventories_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the RegionalInventoryService server but before + it is returned to user code. This `post_list_regional_inventories` interceptor runs + before the `post_list_regional_inventories_with_metadata` interceptor. + """ + return response + + def post_list_regional_inventories_with_metadata(self, response: regionalinventory.ListRegionalInventoriesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regionalinventory.ListRegionalInventoriesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_regional_inventories + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the RegionalInventoryService server but before it is returned to user code. + + We recommend only using this `post_list_regional_inventories_with_metadata` + interceptor in new development instead of the `post_list_regional_inventories` interceptor. + When both interceptors are used, this `post_list_regional_inventories_with_metadata` interceptor runs after the + `post_list_regional_inventories` interceptor. The (possibly modified) response returned by + `post_list_regional_inventories` will be passed to + `post_list_regional_inventories_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class RegionalInventoryServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: RegionalInventoryServiceRestInterceptor + + +class RegionalInventoryServiceRestTransport(_BaseRegionalInventoryServiceRestTransport): + """REST backend synchronous transport for RegionalInventoryService. + + Service to manage regional inventory for products. There is also + separate ``regions`` resource and API to manage regions definitions. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'merchantapi.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[RegionalInventoryServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or RegionalInventoryServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _DeleteRegionalInventory(_BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory, RegionalInventoryServiceRestStub): + def __hash__(self): + return hash("RegionalInventoryServiceRestTransport.DeleteRegionalInventory") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: regionalinventory.DeleteRegionalInventoryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete regional inventory method over HTTP. + + Args: + request (~.regionalinventory.DeleteRegionalInventoryRequest): + The request object. Request message for the ``DeleteRegionalInventory`` + 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 = _BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._get_http_options() + + request, metadata = self._interceptor.pre_delete_regional_inventory(request, metadata) + transcoded_request = _BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient.DeleteRegionalInventory", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "rpcName": "DeleteRegionalInventory", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionalInventoryServiceRestTransport._DeleteRegionalInventory._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 _InsertRegionalInventory(_BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory, RegionalInventoryServiceRestStub): + def __hash__(self): + return hash("RegionalInventoryServiceRestTransport.InsertRegionalInventory") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: regionalinventory.InsertRegionalInventoryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> regionalinventory.RegionalInventory: + r"""Call the insert regional inventory method over HTTP. + + Args: + request (~.regionalinventory.InsertRegionalInventoryRequest): + The request object. Request message for the ``InsertRegionalInventory`` + 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: + ~.regionalinventory.RegionalInventory: + Regional inventory information for the product. + Represents specific information like price and + availability for a given product in a specific + [``region``][google.shopping.merchant.inventories.v1beta.RegionalInventory.region]. + For a list of all accepted attribute values, see the + `regional product inventory data + specification `__. + + """ + + http_options = _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_http_options() + + request, metadata = self._interceptor.pre_insert_regional_inventory(request, metadata) + transcoded_request = _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_transcoded_request(http_options, request) + + body = _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient.InsertRegionalInventory", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "rpcName": "InsertRegionalInventory", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionalInventoryServiceRestTransport._InsertRegionalInventory._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = regionalinventory.RegionalInventory() + pb_resp = regionalinventory.RegionalInventory.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_insert_regional_inventory(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_insert_regional_inventory_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = regionalinventory.RegionalInventory.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient.insert_regional_inventory", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "rpcName": "InsertRegionalInventory", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListRegionalInventories(_BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories, RegionalInventoryServiceRestStub): + def __hash__(self): + return hash("RegionalInventoryServiceRestTransport.ListRegionalInventories") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: regionalinventory.ListRegionalInventoriesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> regionalinventory.ListRegionalInventoriesResponse: + r"""Call the list regional inventories method over HTTP. + + Args: + request (~.regionalinventory.ListRegionalInventoriesRequest): + The request object. Request message for the ``ListRegionalInventories`` + 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: + ~.regionalinventory.ListRegionalInventoriesResponse: + Response message for the ``ListRegionalInventories`` + method. + + """ + + http_options = _BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._get_http_options() + + request, metadata = self._interceptor.pre_list_regional_inventories(request, metadata) + transcoded_request = _BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient.ListRegionalInventories", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "rpcName": "ListRegionalInventories", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionalInventoryServiceRestTransport._ListRegionalInventories._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = regionalinventory.ListRegionalInventoriesResponse() + pb_resp = regionalinventory.ListRegionalInventoriesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_regional_inventories(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_regional_inventories_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = regionalinventory.ListRegionalInventoriesResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient.list_regional_inventories", + extra = { + "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "rpcName": "ListRegionalInventories", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def delete_regional_inventory(self) -> Callable[ + [regionalinventory.DeleteRegionalInventoryRequest], + 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._DeleteRegionalInventory(self._session, self._host, self._interceptor) # type: ignore + + @property + def insert_regional_inventory(self) -> Callable[ + [regionalinventory.InsertRegionalInventoryRequest], + regionalinventory.RegionalInventory]: + # 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._InsertRegionalInventory(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_regional_inventories(self) -> Callable[ + [regionalinventory.ListRegionalInventoriesRequest], + regionalinventory.ListRegionalInventoriesResponse]: + # 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._ListRegionalInventories(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'RegionalInventoryServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest_base.py new file mode 100644 index 000000000000..5da5c1f7431f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest_base.py @@ -0,0 +1,213 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from .base import RegionalInventoryServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_inventories_v1beta.types import regionalinventory + + +class _BaseRegionalInventoryServiceRestTransport(RegionalInventoryServiceTransport): + """Base REST backend transport for RegionalInventoryService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'merchantapi.googleapis.com', + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'merchantapi.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + + class _BaseDeleteRegionalInventory: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/inventories/v1beta/{name=accounts/*/products/*/regionalInventories/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = regionalinventory.DeleteRegionalInventoryRequest.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(_BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseInsertRegionalInventory: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/inventories/v1beta/{parent=accounts/*/products/*}/regionalInventories:insert', + 'body': 'regional_inventory', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = regionalinventory.InsertRegionalInventoryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListRegionalInventories: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/inventories/v1beta/{parent=accounts/*/products/*}/regionalInventories', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = regionalinventory.ListRegionalInventoriesRequest.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(_BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseRegionalInventoryServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/__init__.py new file mode 100644 index 000000000000..77bed1ea7dce --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/__init__.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .localinventory import ( + DeleteLocalInventoryRequest, + InsertLocalInventoryRequest, + ListLocalInventoriesRequest, + ListLocalInventoriesResponse, + LocalInventory, +) +from .regionalinventory import ( + DeleteRegionalInventoryRequest, + InsertRegionalInventoryRequest, + ListRegionalInventoriesRequest, + ListRegionalInventoriesResponse, + RegionalInventory, +) + +__all__ = ( + 'DeleteLocalInventoryRequest', + 'InsertLocalInventoryRequest', + 'ListLocalInventoriesRequest', + 'ListLocalInventoriesResponse', + 'LocalInventory', + 'DeleteRegionalInventoryRequest', + 'InsertRegionalInventoryRequest', + 'ListRegionalInventoriesRequest', + 'ListRegionalInventoriesResponse', + 'RegionalInventory', +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/localinventory.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/localinventory.py new file mode 100644 index 000000000000..9183d2bf4942 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/localinventory.py @@ -0,0 +1,281 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.shopping.type.types import types +from google.type import interval_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.inventories.v1beta', + manifest={ + 'LocalInventory', + 'ListLocalInventoriesRequest', + 'ListLocalInventoriesResponse', + 'InsertLocalInventoryRequest', + 'DeleteLocalInventoryRequest', + }, +) + + +class LocalInventory(proto.Message): + r"""Local inventory information for the product. Represents in-store + information for a specific product at the store specified by + [``storeCode``][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code]. + For a list of all accepted attribute values, see the `local product + inventory data + specification `__. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Output only. The name of the ``LocalInventory`` resource. + Format: + ``accounts/{account}/products/{product}/localInventories/{store_code}`` + account (int): + Output only. The account that owns the + product. This field will be ignored if set by + the client. + store_code (str): + Required. Immutable. Store code (the store ID from your + Business Profile) of the physical store the product is sold + in. See the `Local product inventory data + specification `__ + for more information. + price (google.shopping.type.types.Price): + Price of the product at this store. + sale_price (google.shopping.type.types.Price): + Sale price of the product at this store. Mandatory if + [``salePriceEffectiveDate``][google.shopping.merchant.inventories.v1beta.LocalInventory.sale_price_effective_date] + is defined. + sale_price_effective_date (google.type.interval_pb2.Interval): + The ``TimePeriod`` of the sale at this store. + availability (str): + Availability of the product at this store. For accepted + attribute values, see the `local product inventory data + specification `__ + + This field is a member of `oneof`_ ``_availability``. + quantity (int): + Quantity of the product available at this + store. Must be greater than or equal to zero. + + This field is a member of `oneof`_ ``_quantity``. + pickup_method (str): + Supported pickup method for this product. Unless the value + is ``"not supported"``, this field must be submitted + together with ``pickupSla``. For accepted attribute values, + see the `local product inventory data + specification `__ + + This field is a member of `oneof`_ ``_pickup_method``. + pickup_sla (str): + Relative time period from the order date for an order for + this product, from this store, to be ready for pickup. Must + be submitted with ``pickupMethod``. For accepted attribute + values, see the `local product inventory data + specification `__ + + This field is a member of `oneof`_ ``_pickup_sla``. + instore_product_location (str): + Location of the product inside the store. + Maximum length is 20 bytes. + + This field is a member of `oneof`_ ``_instore_product_location``. + custom_attributes (MutableSequence[google.shopping.type.types.CustomAttribute]): + A list of custom (merchant-provided) attributes. You can + also use ``CustomAttribute`` to submit any attribute of the + data specification in its generic form. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + account: int = proto.Field( + proto.INT64, + number=2, + ) + store_code: str = proto.Field( + proto.STRING, + number=3, + ) + price: types.Price = proto.Field( + proto.MESSAGE, + number=4, + message=types.Price, + ) + sale_price: types.Price = proto.Field( + proto.MESSAGE, + number=5, + message=types.Price, + ) + sale_price_effective_date: interval_pb2.Interval = proto.Field( + proto.MESSAGE, + number=6, + message=interval_pb2.Interval, + ) + availability: str = proto.Field( + proto.STRING, + number=7, + optional=True, + ) + quantity: int = proto.Field( + proto.INT64, + number=8, + optional=True, + ) + pickup_method: str = proto.Field( + proto.STRING, + number=9, + optional=True, + ) + pickup_sla: str = proto.Field( + proto.STRING, + number=10, + optional=True, + ) + instore_product_location: str = proto.Field( + proto.STRING, + number=11, + optional=True, + ) + custom_attributes: MutableSequence[types.CustomAttribute] = proto.RepeatedField( + proto.MESSAGE, + number=12, + message=types.CustomAttribute, + ) + + +class ListLocalInventoriesRequest(proto.Message): + r"""Request message for the ``ListLocalInventories`` method. + + Attributes: + parent (str): + Required. The ``name`` of the parent product to list local + inventories for. Format: + ``accounts/{account}/products/{product}`` + page_size (int): + The maximum number of ``LocalInventory`` resources for the + given product to return. The service returns fewer than this + value if the number of inventories for the given product is + less that than the ``pageSize``. The default value is 25000. + The maximum value is 25000; If a value higher than the + maximum is specified, then the ``pageSize`` will default to + the maximum + page_token (str): + A page token, received from a previous + ``ListLocalInventories`` call. Provide the page token to + retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListLocalInventories`` must match the call that provided + the page token. The token returned as + [nextPageToken][google.shopping.merchant.inventories.v1beta.ListLocalInventoriesResponse.next_page_token] + in the response to the previous request. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListLocalInventoriesResponse(proto.Message): + r"""Response message for the ``ListLocalInventories`` method. + + Attributes: + local_inventories (MutableSequence[google.shopping.merchant_inventories_v1beta.types.LocalInventory]): + The ``LocalInventory`` resources for the given product from + the specified account. + next_page_token (str): + A token, which can be sent as ``pageToken`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + local_inventories: MutableSequence['LocalInventory'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='LocalInventory', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class InsertLocalInventoryRequest(proto.Message): + r"""Request message for the ``InsertLocalInventory`` method. + + Attributes: + parent (str): + Required. The account and product where this inventory will + be inserted. Format: + ``accounts/{account}/products/{product}`` + local_inventory (google.shopping.merchant_inventories_v1beta.types.LocalInventory): + Required. Local inventory information of the product. If the + product already has a ``LocalInventory`` resource for the + same ``storeCode``, full replacement of the + ``LocalInventory`` resource is performed. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + local_inventory: 'LocalInventory' = proto.Field( + proto.MESSAGE, + number=2, + message='LocalInventory', + ) + + +class DeleteLocalInventoryRequest(proto.Message): + r"""Request message for the ``DeleteLocalInventory`` method. + + Attributes: + name (str): + Required. The name of the local inventory for the given + product to delete. Format: + ``accounts/{account}/products/{product}/localInventories/{store_code}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/regionalinventory.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/regionalinventory.py new file mode 100644 index 000000000000..fe06b511d070 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/regionalinventory.py @@ -0,0 +1,236 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.shopping.type.types import types +from google.type import interval_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.inventories.v1beta', + manifest={ + 'RegionalInventory', + 'ListRegionalInventoriesRequest', + 'ListRegionalInventoriesResponse', + 'InsertRegionalInventoryRequest', + 'DeleteRegionalInventoryRequest', + }, +) + + +class RegionalInventory(proto.Message): + r"""Regional inventory information for the product. Represents specific + information like price and availability for a given product in a + specific + [``region``][google.shopping.merchant.inventories.v1beta.RegionalInventory.region]. + For a list of all accepted attribute values, see the `regional + product inventory data + specification `__. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Output only. The name of the ``RegionalInventory`` resource. + Format: + ``{regional_inventory.name=accounts/{account}/products/{product}/regionalInventories/{region}`` + account (int): + Output only. The account that owns the + product. This field will be ignored if set by + the client. + region (str): + Required. Immutable. ID of the region for this + ``RegionalInventory`` resource. See the `Regional + availability and + pricing `__ + for more details. + price (google.shopping.type.types.Price): + Price of the product in this region. + sale_price (google.shopping.type.types.Price): + Sale price of the product in this region. Mandatory if + [``salePriceEffectiveDate``][google.shopping.merchant.inventories.v1beta.RegionalInventory.sale_price_effective_date] + is defined. + sale_price_effective_date (google.type.interval_pb2.Interval): + The ``TimePeriod`` of the sale price in this region. + availability (str): + Availability of the product in this region. For accepted + attribute values, see the `regional product inventory data + specification `__ + + This field is a member of `oneof`_ ``_availability``. + custom_attributes (MutableSequence[google.shopping.type.types.CustomAttribute]): + A list of custom (merchant-provided) attributes. You can + also use ``CustomAttribute`` to submit any attribute of the + data specification in its generic form. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + account: int = proto.Field( + proto.INT64, + number=2, + ) + region: str = proto.Field( + proto.STRING, + number=3, + ) + price: types.Price = proto.Field( + proto.MESSAGE, + number=4, + message=types.Price, + ) + sale_price: types.Price = proto.Field( + proto.MESSAGE, + number=5, + message=types.Price, + ) + sale_price_effective_date: interval_pb2.Interval = proto.Field( + proto.MESSAGE, + number=6, + message=interval_pb2.Interval, + ) + availability: str = proto.Field( + proto.STRING, + number=7, + optional=True, + ) + custom_attributes: MutableSequence[types.CustomAttribute] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=types.CustomAttribute, + ) + + +class ListRegionalInventoriesRequest(proto.Message): + r"""Request message for the ``ListRegionalInventories`` method. + + Attributes: + parent (str): + Required. The ``name`` of the parent product to list + ``RegionalInventory`` resources for. Format: + ``accounts/{account}/products/{product}`` + page_size (int): + The maximum number of ``RegionalInventory`` resources for + the given product to return. The service returns fewer than + this value if the number of inventories for the given + product is less that than the ``pageSize``. The default + value is 25000. The maximum value is 100000; If a value + higher than the maximum is specified, then the ``pageSize`` + will default to the maximum. + page_token (str): + A page token, received from a previous + ``ListRegionalInventories`` call. Provide the page token to + retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListRegionalInventories`` must match the call that + provided the page token. The token returned as + [nextPageToken][google.shopping.merchant.inventories.v1beta.ListRegionalInventoriesResponse.next_page_token] + in the response to the previous request. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListRegionalInventoriesResponse(proto.Message): + r"""Response message for the ``ListRegionalInventories`` method. + + Attributes: + regional_inventories (MutableSequence[google.shopping.merchant_inventories_v1beta.types.RegionalInventory]): + The ``RegionalInventory`` resources for the given product + from the specified account. + next_page_token (str): + A token, which can be sent as ``pageToken`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + regional_inventories: MutableSequence['RegionalInventory'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='RegionalInventory', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class InsertRegionalInventoryRequest(proto.Message): + r"""Request message for the ``InsertRegionalInventory`` method. + + Attributes: + parent (str): + Required. The account and product where this inventory will + be inserted. Format: + ``accounts/{account}/products/{product}`` + regional_inventory (google.shopping.merchant_inventories_v1beta.types.RegionalInventory): + Required. Regional inventory information to add to the + product. If the product already has a ``RegionalInventory`` + resource for the same ``region``, full replacement of the + ``RegionalInventory`` resource is performed. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + regional_inventory: 'RegionalInventory' = proto.Field( + proto.MESSAGE, + number=2, + message='RegionalInventory', + ) + + +class DeleteRegionalInventoryRequest(proto.Message): + r"""Request message for the ``DeleteRegionalInventory`` method. + + Attributes: + name (str): + Required. The name of the ``RegionalInventory`` resource to + delete. Format: + ``accounts/{account}/products/{product}/regionalInventories/{region}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/mypy.ini b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/noxfile.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/noxfile.py new file mode 100644 index 000000000000..084984b159e7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/noxfile.py @@ -0,0 +1,591 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import re +import shutil + +from typing import Dict, List +import warnings + +import nox + +BLACK_VERSION = "black[jupyter]==23.7.0" +ISORT_VERSION = "isort==5.11.0" + +LINT_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] + +DEFAULT_PYTHON_VERSION = ALL_PYTHON[-1] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = "google-shopping-merchant-inventories" + +UNIT_TEST_STANDARD_DEPENDENCIES = [ + "mock", + "asyncmock", + "pytest", + "pytest-cov", + "pytest-asyncio", +] +UNIT_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] +UNIT_TEST_LOCAL_DEPENDENCIES: List[str] = [] +UNIT_TEST_DEPENDENCIES: List[str] = [] +UNIT_TEST_EXTRAS: List[str] = [] +UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} + +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] +SYSTEM_TEST_STANDARD_DEPENDENCIES = [ + "mock", + "pytest", + "google-cloud-testutils", +] +SYSTEM_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_LOCAL_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_EXTRAS: List[str] = [] +SYSTEM_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} + +nox.options.sessions = [ + "unit", + "system", + "cover", + "lint", + "lint_setup_py", + "blacken", + "docs", +] + +# Error if a python version is missing +nox.options.error_on_missing_interpreters = True + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + "mypy", + "types-requests", + "types-protobuf", + ) + session.install(".") + session.run( + "mypy", + "-p", + "google", + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install("google-cloud-testutils") + session.install(".") + + session.run( + "lower-bound-checker", + "update", + "--package-name", + PACKAGE_NAME, + "--constraints-file", + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install("google-cloud-testutils") + session.install(".") + + session.run( + "lower-bound-checker", + "check", + "--package-name", + PACKAGE_NAME, + "--constraints-file", + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *LINT_PATHS, + ) + + session.run("flake8", "google", "tests") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *LINT_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def format(session): + """ + Run isort to sort imports. Then run black + to format code to uniform standard. + """ + session.install(BLACK_VERSION, ISORT_VERSION) + # Use the --fss option to sort imports using strict alphabetical order. + # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections + session.run( + "isort", + "--fss", + *LINT_PATHS, + ) + session.run( + "black", + *LINT_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("setuptools", "docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") + + +def install_unittest_dependencies(session, *constraints): + standard_deps = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_DEPENDENCIES + session.install(*standard_deps, *constraints) + + if UNIT_TEST_EXTERNAL_DEPENDENCIES: + warnings.warn( + "'unit_test_external_dependencies' is deprecated. Instead, please " + "use 'unit_test_dependencies' or 'unit_test_local_dependencies'.", + DeprecationWarning, + ) + session.install(*UNIT_TEST_EXTERNAL_DEPENDENCIES, *constraints) + + if UNIT_TEST_LOCAL_DEPENDENCIES: + session.install(*UNIT_TEST_LOCAL_DEPENDENCIES, *constraints) + + if UNIT_TEST_EXTRAS_BY_PYTHON: + extras = UNIT_TEST_EXTRAS_BY_PYTHON.get(session.python, []) + elif UNIT_TEST_EXTRAS: + extras = UNIT_TEST_EXTRAS + else: + extras = [] + + if extras: + session.install("-e", f".[{','.join(extras)}]", *constraints) + else: + session.install("-e", ".", *constraints) + + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + ["python", "upb", "cpp"], +) +def unit(session, protobuf_implementation): + # Install all test dependencies, then install this package in-place. + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): + session.skip("cpp implementation is not supported in python 3.11+") + + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) + install_unittest_dependencies(session, "-c", constraints_path) + + # TODO(https://github.com/googleapis/synthtool/issues/1976): + # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. + # The 'cpp' implementation requires Protobuf<4. + if protobuf_implementation == "cpp": + session.install("protobuf<4") + + # Run py.test against the unit tests. + session.run( + "py.test", + "--quiet", + f"--junitxml=unit_{session.python}_sponge_log.xml", + "--cov=google", + "--cov=tests/unit", + "--cov-append", + "--cov-config=.coveragerc", + "--cov-report=", + "--cov-fail-under=0", + os.path.join("tests", "unit"), + *session.posargs, + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +def install_systemtest_dependencies(session, *constraints): + session.install("--pre", "grpcio") + + session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_EXTERNAL_DEPENDENCIES: + session.install(*SYSTEM_TEST_EXTERNAL_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_LOCAL_DEPENDENCIES: + session.install("-e", *SYSTEM_TEST_LOCAL_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_DEPENDENCIES: + session.install("-e", *SYSTEM_TEST_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_EXTRAS_BY_PYTHON: + extras = SYSTEM_TEST_EXTRAS_BY_PYTHON.get(session.python, []) + elif SYSTEM_TEST_EXTRAS: + extras = SYSTEM_TEST_EXTRAS + else: + extras = [] + + if extras: + session.install("-e", f".[{','.join(extras)}]", *constraints) + else: + session.install("-e", ".", *constraints) + + +@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) +def system(session): + """Run the system test suite.""" + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) + system_test_path = os.path.join("tests", "system.py") + system_test_folder_path = os.path.join("tests", "system") + + # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. + if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": + session.skip("RUN_SYSTEM_TESTS is set to false, skipping") + # Install pyopenssl for mTLS testing. + if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": + session.install("pyopenssl") + + system_test_exists = os.path.exists(system_test_path) + system_test_folder_exists = os.path.exists(system_test_folder_path) + # Sanity check: only run tests if found. + if not system_test_exists and not system_test_folder_exists: + session.skip("System tests were not found") + + install_systemtest_dependencies(session, "-c", constraints_path) + + # Run py.test against the system tests. + if system_test_exists: + session.run( + "py.test", + "--quiet", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_path, + *session.posargs, + ) + if system_test_folder_exists: + session.run( + "py.test", + "--quiet", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_folder_path, + *session.posargs, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python="3.10") +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install( + # We need to pin to specific versions of the `sphinxcontrib-*` packages + # which still support sphinx 4.x. + # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 + # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. + "sphinxcontrib-applehelp==1.0.4", + "sphinxcontrib-devhelp==1.0.2", + "sphinxcontrib-htmlhelp==2.0.1", + "sphinxcontrib-qthelp==1.0.3", + "sphinxcontrib-serializinghtml==1.1.5", + "sphinx==4.5.0", + "alabaster", + "recommonmark", + ) + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python="3.10") +def docfx(session): + """Build the docfx yaml files for this library.""" + + session.install("-e", ".") + session.install( + # We need to pin to specific versions of the `sphinxcontrib-*` packages + # which still support sphinx 4.x. + # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 + # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. + "sphinxcontrib-applehelp==1.0.4", + "sphinxcontrib-devhelp==1.0.2", + "sphinxcontrib-htmlhelp==2.0.1", + "sphinxcontrib-qthelp==1.0.3", + "sphinxcontrib-serializinghtml==1.1.5", + "gcp-sphinx-docfx-yaml", + "alabaster", + "recommonmark", + ) + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-T", # show full traceback on exception + "-N", # no colors + "-D", + ( + "extensions=sphinx.ext.autodoc," + "sphinx.ext.autosummary," + "docfx_yaml.extension," + "sphinx.ext.intersphinx," + "sphinx.ext.coverage," + "sphinx.ext.napoleon," + "sphinx.ext.todo," + "sphinx.ext.viewcode," + "recommonmark" + ), + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +@nox.parametrize( + "protobuf_implementation", + ["python", "upb", "cpp"], +) +def prerelease_deps(session, protobuf_implementation): + """ + Run all tests with pre-release versions of dependencies installed + rather than the standard non pre-release versions. + Pre-release versions can be installed using + `pip install --pre `. + """ + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): + session.skip("cpp implementation is not supported in python 3.11+") + + # Install all dependencies + session.install("-e", ".") + + # Install dependencies for the unit test environment + unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES + session.install(*unit_deps_all) + + # Install dependencies for the system test environment + system_deps_all = ( + SYSTEM_TEST_STANDARD_DEPENDENCIES + + SYSTEM_TEST_EXTERNAL_DEPENDENCIES + + SYSTEM_TEST_EXTRAS + ) + session.install(*system_deps_all) + + # Because we test minimum dependency versions on the minimum Python + # version, the first version we test with in the unit tests sessions has a + # constraints file containing all dependencies and extras. + with open( + CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + # Install dependencies specified in `testing/constraints-X.txt`. + session.install(*constraints_deps) + + # Note: If a dependency is added to the `prerel_deps` list, + # the `core_dependencies_from_source` list in the `core_deps_from_source` + # nox session should also be updated. + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + "grpc-google-iam-v1", + "grpcio", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--ignore-installed", dep) + # TODO(https://github.com/grpc/grpc/issues/38965): Add `grpcio-status`` + # to the dictionary below once this bug is fixed. + # TODO(https://github.com/googleapis/google-cloud-python/issues/13643): Add + # `googleapis-common-protos` and `grpc-google-iam-v1` to the dictionary below + # once this bug is fixed. + package_namespaces = { + "google-api-core": "google.api_core", + "google-auth": "google.auth", + "grpcio": "grpc", + "protobuf": "google.protobuf", + "proto-plus": "proto", + } + + version_namespace = package_namespaces.get(dep) + + print(f"Installed {dep}") + if version_namespace: + session.run( + "python", + "-c", + f"import {version_namespace}; print({version_namespace}.__version__)", + ) + + session.run( + "py.test", + "tests/unit", + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +@nox.parametrize( + "protobuf_implementation", + ["python", "upb"], +) +def core_deps_from_source(session, protobuf_implementation): + """Run all tests with core dependencies installed from source + rather than pulling the dependencies from PyPI. + """ + + # Install all dependencies + session.install("-e", ".") + + # Install dependencies for the unit test environment + unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES + session.install(*unit_deps_all) + + # Install dependencies for the system test environment + system_deps_all = ( + SYSTEM_TEST_STANDARD_DEPENDENCIES + + SYSTEM_TEST_EXTERNAL_DEPENDENCIES + + SYSTEM_TEST_EXTRAS + ) + session.install(*system_deps_all) + + # Because we test minimum dependency versions on the minimum Python + # version, the first version we test with in the unit tests sessions has a + # constraints file containing all dependencies and extras. + with open( + CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + # Install dependencies specified in `testing/constraints-X.txt`. + session.install(*constraints_deps) + + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and + # `grpcio-status` should be added to the list below so that they are installed from source, + # rather than PyPI. + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2357): `protobuf` should be + # added to the list below so that it is installed from source, rather than PyPI + # Note: If a dependency is added to the `core_dependencies_from_source` list, + # the `prerel_deps` list in the `prerelease_deps` nox session should also be updated. + core_dependencies_from_source = [ + "googleapis-common-protos @ git+https://github.com/googleapis/google-cloud-python#egg=googleapis-common-protos&subdirectory=packages/googleapis-common-protos", + "google-api-core @ git+https://github.com/googleapis/python-api-core.git", + "google-auth @ git+https://github.com/googleapis/google-auth-library-python.git", + "grpc-google-iam-v1 @ git+https://github.com/googleapis/google-cloud-python#egg=grpc-google-iam-v1&subdirectory=packages/grpc-google-iam-v1", + "proto-plus @ git+https://github.com/googleapis/proto-plus-python.git", + ] + + for dep in core_dependencies_from_source: + session.install(dep, "--no-deps", "--ignore-installed") + print(f"Installed {dep}") + + session.run( + "py.test", + "tests/unit", + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_async.py new file mode 100644 index 000000000000..b943553049d3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteLocalInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1beta_generated_LocalInventoryService_DeleteLocalInventory_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1beta + + +async def sample_delete_local_inventory(): + # Create a client + client = merchant_inventories_v1beta.LocalInventoryServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.DeleteLocalInventoryRequest( + name="name_value", + ) + + # Make the request + await client.delete_local_inventory(request=request) + + +# [END merchantapi_v1beta_generated_LocalInventoryService_DeleteLocalInventory_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_sync.py new file mode 100644 index 000000000000..8c7fd4ce178e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteLocalInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1beta_generated_LocalInventoryService_DeleteLocalInventory_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1beta + + +def sample_delete_local_inventory(): + # Create a client + client = merchant_inventories_v1beta.LocalInventoryServiceClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.DeleteLocalInventoryRequest( + name="name_value", + ) + + # Make the request + client.delete_local_inventory(request=request) + + +# [END merchantapi_v1beta_generated_LocalInventoryService_DeleteLocalInventory_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_async.py new file mode 100644 index 000000000000..06103e944a86 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InsertLocalInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1beta_generated_LocalInventoryService_InsertLocalInventory_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1beta + + +async def sample_insert_local_inventory(): + # Create a client + client = merchant_inventories_v1beta.LocalInventoryServiceAsyncClient() + + # Initialize request argument(s) + local_inventory = merchant_inventories_v1beta.LocalInventory() + local_inventory.store_code = "store_code_value" + + request = merchant_inventories_v1beta.InsertLocalInventoryRequest( + parent="parent_value", + local_inventory=local_inventory, + ) + + # Make the request + response = await client.insert_local_inventory(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_LocalInventoryService_InsertLocalInventory_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_sync.py new file mode 100644 index 000000000000..7f36fb1e49d8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InsertLocalInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1beta_generated_LocalInventoryService_InsertLocalInventory_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1beta + + +def sample_insert_local_inventory(): + # Create a client + client = merchant_inventories_v1beta.LocalInventoryServiceClient() + + # Initialize request argument(s) + local_inventory = merchant_inventories_v1beta.LocalInventory() + local_inventory.store_code = "store_code_value" + + request = merchant_inventories_v1beta.InsertLocalInventoryRequest( + parent="parent_value", + local_inventory=local_inventory, + ) + + # Make the request + response = client.insert_local_inventory(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_LocalInventoryService_InsertLocalInventory_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_async.py new file mode 100644 index 000000000000..28c3b798d98a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1beta_generated_LocalInventoryService_ListLocalInventories_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1beta + + +async def sample_list_local_inventories(): + # Create a client + client = merchant_inventories_v1beta.LocalInventoryServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.ListLocalInventoriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_local_inventories(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_LocalInventoryService_ListLocalInventories_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_sync.py new file mode 100644 index 000000000000..0da9a3949ef0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListLocalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1beta_generated_LocalInventoryService_ListLocalInventories_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1beta + + +def sample_list_local_inventories(): + # Create a client + client = merchant_inventories_v1beta.LocalInventoryServiceClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.ListLocalInventoriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_local_inventories(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_LocalInventoryService_ListLocalInventories_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_async.py new file mode 100644 index 000000000000..a94f70d57db0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteRegionalInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1beta_generated_RegionalInventoryService_DeleteRegionalInventory_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1beta + + +async def sample_delete_regional_inventory(): + # Create a client + client = merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.DeleteRegionalInventoryRequest( + name="name_value", + ) + + # Make the request + await client.delete_regional_inventory(request=request) + + +# [END merchantapi_v1beta_generated_RegionalInventoryService_DeleteRegionalInventory_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_sync.py new file mode 100644 index 000000000000..e128acbf9531 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteRegionalInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1beta_generated_RegionalInventoryService_DeleteRegionalInventory_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1beta + + +def sample_delete_regional_inventory(): + # Create a client + client = merchant_inventories_v1beta.RegionalInventoryServiceClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.DeleteRegionalInventoryRequest( + name="name_value", + ) + + # Make the request + client.delete_regional_inventory(request=request) + + +# [END merchantapi_v1beta_generated_RegionalInventoryService_DeleteRegionalInventory_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_async.py new file mode 100644 index 000000000000..39a0f6a7e767 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InsertRegionalInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1beta_generated_RegionalInventoryService_InsertRegionalInventory_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1beta + + +async def sample_insert_regional_inventory(): + # Create a client + client = merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient() + + # Initialize request argument(s) + regional_inventory = merchant_inventories_v1beta.RegionalInventory() + regional_inventory.region = "region_value" + + request = merchant_inventories_v1beta.InsertRegionalInventoryRequest( + parent="parent_value", + regional_inventory=regional_inventory, + ) + + # Make the request + response = await client.insert_regional_inventory(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_RegionalInventoryService_InsertRegionalInventory_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_sync.py new file mode 100644 index 000000000000..b8b5089a2b83 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InsertRegionalInventory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1beta_generated_RegionalInventoryService_InsertRegionalInventory_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1beta + + +def sample_insert_regional_inventory(): + # Create a client + client = merchant_inventories_v1beta.RegionalInventoryServiceClient() + + # Initialize request argument(s) + regional_inventory = merchant_inventories_v1beta.RegionalInventory() + regional_inventory.region = "region_value" + + request = merchant_inventories_v1beta.InsertRegionalInventoryRequest( + parent="parent_value", + regional_inventory=regional_inventory, + ) + + # Make the request + response = client.insert_regional_inventory(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_RegionalInventoryService_InsertRegionalInventory_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_async.py new file mode 100644 index 000000000000..33d6df5c8f45 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListRegionalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1beta_generated_RegionalInventoryService_ListRegionalInventories_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1beta + + +async def sample_list_regional_inventories(): + # Create a client + client = merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.ListRegionalInventoriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_regional_inventories(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_RegionalInventoryService_ListRegionalInventories_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_sync.py new file mode 100644 index 000000000000..7c23ca47ca05 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListRegionalInventories +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-shopping-merchant-inventories + + +# [START merchantapi_v1beta_generated_RegionalInventoryService_ListRegionalInventories_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.shopping import merchant_inventories_v1beta + + +def sample_list_regional_inventories(): + # Create a client + client = merchant_inventories_v1beta.RegionalInventoryServiceClient() + + # Initialize request argument(s) + request = merchant_inventories_v1beta.ListRegionalInventoriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_regional_inventories(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_RegionalInventoryService_ListRegionalInventories_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1beta.json b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1beta.json new file mode 100644 index 000000000000..73ddfcf94070 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1beta.json @@ -0,0 +1,953 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.shopping.merchant.inventories.v1beta", + "version": "v1beta" + } + ], + "language": "PYTHON", + "name": "google-shopping-merchant-inventories", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceAsyncClient", + "shortName": "LocalInventoryServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceAsyncClient.delete_local_inventory", + "method": { + "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService.DeleteLocalInventory", + "service": { + "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "shortName": "LocalInventoryService" + }, + "shortName": "DeleteLocalInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1beta.types.DeleteLocalInventoryRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_local_inventory" + }, + "description": "Sample for DeleteLocalInventory", + "file": "merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_LocalInventoryService_DeleteLocalInventory_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceClient", + "shortName": "LocalInventoryServiceClient" + }, + "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceClient.delete_local_inventory", + "method": { + "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService.DeleteLocalInventory", + "service": { + "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "shortName": "LocalInventoryService" + }, + "shortName": "DeleteLocalInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1beta.types.DeleteLocalInventoryRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_local_inventory" + }, + "description": "Sample for DeleteLocalInventory", + "file": "merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_LocalInventoryService_DeleteLocalInventory_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceAsyncClient", + "shortName": "LocalInventoryServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceAsyncClient.insert_local_inventory", + "method": { + "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService.InsertLocalInventory", + "service": { + "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "shortName": "LocalInventoryService" + }, + "shortName": "InsertLocalInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1beta.types.InsertLocalInventoryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_inventories_v1beta.types.LocalInventory", + "shortName": "insert_local_inventory" + }, + "description": "Sample for InsertLocalInventory", + "file": "merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_LocalInventoryService_InsertLocalInventory_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceClient", + "shortName": "LocalInventoryServiceClient" + }, + "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceClient.insert_local_inventory", + "method": { + "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService.InsertLocalInventory", + "service": { + "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "shortName": "LocalInventoryService" + }, + "shortName": "InsertLocalInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1beta.types.InsertLocalInventoryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_inventories_v1beta.types.LocalInventory", + "shortName": "insert_local_inventory" + }, + "description": "Sample for InsertLocalInventory", + "file": "merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_LocalInventoryService_InsertLocalInventory_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceAsyncClient", + "shortName": "LocalInventoryServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceAsyncClient.list_local_inventories", + "method": { + "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService.ListLocalInventories", + "service": { + "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "shortName": "LocalInventoryService" + }, + "shortName": "ListLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_inventories_v1beta.services.local_inventory_service.pagers.ListLocalInventoriesAsyncPager", + "shortName": "list_local_inventories" + }, + "description": "Sample for ListLocalInventories", + "file": "merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_LocalInventoryService_ListLocalInventories_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceClient", + "shortName": "LocalInventoryServiceClient" + }, + "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceClient.list_local_inventories", + "method": { + "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService.ListLocalInventories", + "service": { + "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", + "shortName": "LocalInventoryService" + }, + "shortName": "ListLocalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_inventories_v1beta.services.local_inventory_service.pagers.ListLocalInventoriesPager", + "shortName": "list_local_inventories" + }, + "description": "Sample for ListLocalInventories", + "file": "merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_LocalInventoryService_ListLocalInventories_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient", + "shortName": "RegionalInventoryServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient.delete_regional_inventory", + "method": { + "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService.DeleteRegionalInventory", + "service": { + "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "shortName": "RegionalInventoryService" + }, + "shortName": "DeleteRegionalInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1beta.types.DeleteRegionalInventoryRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_regional_inventory" + }, + "description": "Sample for DeleteRegionalInventory", + "file": "merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_RegionalInventoryService_DeleteRegionalInventory_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceClient", + "shortName": "RegionalInventoryServiceClient" + }, + "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceClient.delete_regional_inventory", + "method": { + "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService.DeleteRegionalInventory", + "service": { + "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "shortName": "RegionalInventoryService" + }, + "shortName": "DeleteRegionalInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1beta.types.DeleteRegionalInventoryRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_regional_inventory" + }, + "description": "Sample for DeleteRegionalInventory", + "file": "merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_RegionalInventoryService_DeleteRegionalInventory_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient", + "shortName": "RegionalInventoryServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient.insert_regional_inventory", + "method": { + "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService.InsertRegionalInventory", + "service": { + "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "shortName": "RegionalInventoryService" + }, + "shortName": "InsertRegionalInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1beta.types.InsertRegionalInventoryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_inventories_v1beta.types.RegionalInventory", + "shortName": "insert_regional_inventory" + }, + "description": "Sample for InsertRegionalInventory", + "file": "merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_RegionalInventoryService_InsertRegionalInventory_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceClient", + "shortName": "RegionalInventoryServiceClient" + }, + "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceClient.insert_regional_inventory", + "method": { + "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService.InsertRegionalInventory", + "service": { + "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "shortName": "RegionalInventoryService" + }, + "shortName": "InsertRegionalInventory" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1beta.types.InsertRegionalInventoryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_inventories_v1beta.types.RegionalInventory", + "shortName": "insert_regional_inventory" + }, + "description": "Sample for InsertRegionalInventory", + "file": "merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_RegionalInventoryService_InsertRegionalInventory_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient", + "shortName": "RegionalInventoryServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient.list_regional_inventories", + "method": { + "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService.ListRegionalInventories", + "service": { + "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "shortName": "RegionalInventoryService" + }, + "shortName": "ListRegionalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.pagers.ListRegionalInventoriesAsyncPager", + "shortName": "list_regional_inventories" + }, + "description": "Sample for ListRegionalInventories", + "file": "merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_RegionalInventoryService_ListRegionalInventories_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceClient", + "shortName": "RegionalInventoryServiceClient" + }, + "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceClient.list_regional_inventories", + "method": { + "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService.ListRegionalInventories", + "service": { + "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", + "shortName": "RegionalInventoryService" + }, + "shortName": "ListRegionalInventories" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.pagers.ListRegionalInventoriesPager", + "shortName": "list_regional_inventories" + }, + "description": "Sample for ListRegionalInventories", + "file": "merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_RegionalInventoryService_ListRegionalInventories_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/scripts/fixup_merchant_inventories_v1beta_keywords.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/scripts/fixup_merchant_inventories_v1beta_keywords.py new file mode 100644 index 000000000000..02d464643567 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/scripts/fixup_merchant_inventories_v1beta_keywords.py @@ -0,0 +1,181 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class merchant_inventoriesCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'delete_local_inventory': ('name', ), + 'delete_regional_inventory': ('name', ), + 'insert_local_inventory': ('parent', 'local_inventory', ), + 'insert_regional_inventory': ('parent', 'regional_inventory', ), + 'list_local_inventories': ('parent', 'page_size', 'page_token', ), + 'list_regional_inventories': ('parent', 'page_size', 'page_token', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=merchant_inventoriesCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the merchant_inventories client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/setup.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/setup.py new file mode 100644 index 000000000000..4fd17ebb95a5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/setup.py @@ -0,0 +1,99 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import re + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-shopping-merchant-inventories' + + +description = "Google Shopping Merchant Inventories API client library" + +version = None + +with open(os.path.join(package_root, 'google/shopping/merchant_inventories/gapic_version.py')) as fp: + version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) + assert (len(version_candidates) == 1) + version = version_candidates[0] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.1, <3.0.0,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0", + "proto-plus >= 1.25.0, <2.0.0; python_version >= '3.13'", + "protobuf>=3.20.2,<7.0.0,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", + "google-shopping-type >= 0.1.6, <1.0.0", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-inventories" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.find_namespace_packages() + if package.startswith("google") +] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + extras_require=extras, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.10.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.10.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.11.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.11.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.12.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.12.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.13.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.13.txt new file mode 100644 index 000000000000..0112695e5bbb --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.13.txt @@ -0,0 +1,12 @@ +# We use the constraints file for the latest Python version +# (currently this file) to check that the latest +# major versions of dependencies are supported in setup.py. +# List all library dependencies and extras in this file. +# Require the latest major version be installed for each dependency. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# Then this file should have google-cloud-foo>=1 +google-api-core>=2 +google-auth>=2 +proto-plus>=1 +protobuf>=6 +google-shopping-type>=0 diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.7.txt new file mode 100644 index 000000000000..2af887ec8ba0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.7.txt @@ -0,0 +1,11 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.1 +google-auth==2.14.1 +proto-plus==1.22.3 +protobuf==3.20.2 +google-shopping-type==0.1.6 diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.8.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.8.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.9.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.9.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_local_inventory_service.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_local_inventory_service.py new file mode 100644 index 000000000000..91fcbd7af71c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_local_inventory_service.py @@ -0,0 +1,3666 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +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 proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +try: + from google.auth.aio import credentials as ga_credentials_async + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import 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 +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +from google.protobuf import timestamp_pb2 # type: ignore +from google.shopping.merchant_inventories_v1beta.services.local_inventory_service import LocalInventoryServiceAsyncClient +from google.shopping.merchant_inventories_v1beta.services.local_inventory_service import LocalInventoryServiceClient +from google.shopping.merchant_inventories_v1beta.services.local_inventory_service import pagers +from google.shopping.merchant_inventories_v1beta.services.local_inventory_service import transports +from google.shopping.merchant_inventories_v1beta.types import localinventory +from google.shopping.type.types import types +from google.type import interval_pb2 # type: ignore +import google.auth + + + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + +# 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 + +# 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 + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert LocalInventoryServiceClient._get_default_mtls_endpoint(None) is None + assert LocalInventoryServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert LocalInventoryServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert LocalInventoryServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert LocalInventoryServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert LocalInventoryServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert LocalInventoryServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert LocalInventoryServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert LocalInventoryServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + LocalInventoryServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert LocalInventoryServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert LocalInventoryServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert LocalInventoryServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + LocalInventoryServiceClient._read_environment_variables() + 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 LocalInventoryServiceClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert LocalInventoryServiceClient._get_client_cert_source(None, False) is None + assert LocalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert LocalInventoryServiceClient._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 LocalInventoryServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert LocalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(LocalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceClient)) +@mock.patch.object(LocalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = LocalInventoryServiceClient._DEFAULT_UNIVERSE + default_endpoint = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert LocalInventoryServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert LocalInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + assert LocalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert LocalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "always") == LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + assert LocalInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + assert LocalInventoryServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert LocalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + LocalInventoryServiceClient._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 LocalInventoryServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert LocalInventoryServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert LocalInventoryServiceClient._get_universe_domain(None, None) == LocalInventoryServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + LocalInventoryServiceClient._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) +]) +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) + client = LocalInventoryServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + +@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") + client = LocalInventoryServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + +@pytest.mark.parametrize("client_class,transport_name", [ + (LocalInventoryServiceClient, "grpc"), + (LocalInventoryServiceAsyncClient, "grpc_asyncio"), + (LocalInventoryServiceClient, "rest"), +]) +def test_local_inventory_service_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: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'merchantapi.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://merchantapi.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.LocalInventoryServiceGrpcTransport, "grpc"), + (transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.LocalInventoryServiceRestTransport, "rest"), +]) +def test_local_inventory_service_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: + 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", [ + (LocalInventoryServiceClient, "grpc"), + (LocalInventoryServiceAsyncClient, "grpc_asyncio"), + (LocalInventoryServiceClient, "rest"), +]) +def test_local_inventory_service_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: + factory.return_value = creds + 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) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'merchantapi.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://merchantapi.googleapis.com' + ) + + +def test_local_inventory_service_client_get_transport_class(): + transport = LocalInventoryServiceClient.get_transport_class() + available_transports = [ + transports.LocalInventoryServiceGrpcTransport, + transports.LocalInventoryServiceRestTransport, + ] + assert transport in available_transports + + transport = LocalInventoryServiceClient.get_transport_class("grpc") + assert transport == transports.LocalInventoryServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc"), + (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest"), +]) +@mock.patch.object(LocalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceClient)) +@mock.patch.object(LocalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceAsyncClient)) +def test_local_inventory_service_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(LocalInventoryServiceClient, '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(LocalInventoryServiceClient, '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: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + 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=None, + ) + + # 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: + 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), + 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=None, + ) + + # 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: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + 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=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) 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`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + 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: + 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), + 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", [ + (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc", "true"), + (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc", "false"), + (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest", "true"), + (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(LocalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceClient)) +@mock.patch.object(LocalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_local_inventory_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, 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) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # 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): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # 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): + 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), + 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=None, + ) + + +@pytest.mark.parametrize("client_class", [ + LocalInventoryServiceClient, LocalInventoryServiceAsyncClient +]) +@mock.patch.object(LocalInventoryServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LocalInventoryServiceClient)) +@mock.patch.object(LocalInventoryServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LocalInventoryServiceAsyncClient)) +def test_local_inventory_service_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) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + 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) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + 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 "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # 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): + 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() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) 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`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + LocalInventoryServiceClient, LocalInventoryServiceAsyncClient +]) +@mock.patch.object(LocalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceClient)) +@mock.patch.object(LocalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceAsyncClient)) +def test_local_inventory_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = LocalInventoryServiceClient._DEFAULT_UNIVERSE + default_endpoint = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = LocalInventoryServiceClient._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()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + 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()) + 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) + + # 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. + options = client_options.ClientOptions() + 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()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc"), + (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest"), +]) +def test_local_inventory_service_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: + 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), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc", grpc_helpers), + (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest", None), +]) +def test_local_inventory_service_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" + ) + + 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), + 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=None, + ) + +def test_local_inventory_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_inventories_v1beta.services.local_inventory_service.transports.LocalInventoryServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = LocalInventoryServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + 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=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc", grpc_helpers), + (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_local_inventory_service_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" + ) + + 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), + 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=None, + ) + + # 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: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "merchantapi.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/content', +), + scopes=None, + default_host="merchantapi.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + localinventory.ListLocalInventoriesRequest, + dict, +]) +def test_list_local_inventories(request_type, transport: str = 'grpc'): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = localinventory.ListLocalInventoriesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = localinventory.ListLocalInventoriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListLocalInventoriesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_local_inventories_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = localinventory.ListLocalInventoriesRequest( + 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_local_inventories), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_local_inventories(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == localinventory.ListLocalInventoriesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_local_inventories_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_local_inventories in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_local_inventories] = mock_rpc + request = {} + client.list_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_local_inventories(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_local_inventories_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_local_inventories 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_local_inventories] = mock_rpc + + request = {} + await client.list_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_local_inventories(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_local_inventories_async(transport: str = 'grpc_asyncio', request_type=localinventory.ListLocalInventoriesRequest): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(localinventory.ListLocalInventoriesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = localinventory.ListLocalInventoriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListLocalInventoriesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_local_inventories_async_from_dict(): + await test_list_local_inventories_async(request_type=dict) + +def test_list_local_inventories_field_headers(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = localinventory.ListLocalInventoriesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + call.return_value = localinventory.ListLocalInventoriesResponse() + client.list_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_local_inventories_field_headers_async(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = localinventory.ListLocalInventoriesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.ListLocalInventoriesResponse()) + await client.list_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_local_inventories_flattened(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = localinventory.ListLocalInventoriesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_local_inventories( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_local_inventories_flattened_error(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_local_inventories( + localinventory.ListLocalInventoriesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_local_inventories_flattened_async(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = localinventory.ListLocalInventoriesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.ListLocalInventoriesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_local_inventories( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_local_inventories_flattened_error_async(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_local_inventories( + localinventory.ListLocalInventoriesRequest(), + parent='parent_value', + ) + + +def test_list_local_inventories_pager(transport_name: str = "grpc"): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + next_page_token='abc', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[], + next_page_token='def', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + ], + next_page_token='ghi', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_local_inventories(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, localinventory.LocalInventory) + for i in results) +def test_list_local_inventories_pages(transport_name: str = "grpc"): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + next_page_token='abc', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[], + next_page_token='def', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + ], + next_page_token='ghi', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + ), + RuntimeError, + ) + pages = list(client.list_local_inventories(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_local_inventories_async_pager(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + next_page_token='abc', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[], + next_page_token='def', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + ], + next_page_token='ghi', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_local_inventories(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, localinventory.LocalInventory) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_local_inventories_async_pages(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + next_page_token='abc', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[], + next_page_token='def', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + ], + next_page_token='ghi', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_local_inventories(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + localinventory.InsertLocalInventoryRequest, + dict, +]) +def test_insert_local_inventory(request_type, transport: str = 'grpc'): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_local_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = localinventory.LocalInventory( + name='name_value', + account=749, + store_code='store_code_value', + availability='availability_value', + quantity=895, + pickup_method='pickup_method_value', + pickup_sla='pickup_sla_value', + instore_product_location='instore_product_location_value', + ) + response = client.insert_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = localinventory.InsertLocalInventoryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, localinventory.LocalInventory) + assert response.name == 'name_value' + assert response.account == 749 + assert response.store_code == 'store_code_value' + assert response.availability == 'availability_value' + assert response.quantity == 895 + assert response.pickup_method == 'pickup_method_value' + assert response.pickup_sla == 'pickup_sla_value' + assert response.instore_product_location == 'instore_product_location_value' + + +def test_insert_local_inventory_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = localinventory.InsertLocalInventoryRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_local_inventory), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.insert_local_inventory(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == localinventory.InsertLocalInventoryRequest( + parent='parent_value', + ) + +def test_insert_local_inventory_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.insert_local_inventory in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.insert_local_inventory] = mock_rpc + request = {} + client.insert_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.insert_local_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_insert_local_inventory_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.insert_local_inventory 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.insert_local_inventory] = mock_rpc + + request = {} + await client.insert_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.insert_local_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_insert_local_inventory_async(transport: str = 'grpc_asyncio', request_type=localinventory.InsertLocalInventoryRequest): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_local_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(localinventory.LocalInventory( + name='name_value', + account=749, + store_code='store_code_value', + availability='availability_value', + quantity=895, + pickup_method='pickup_method_value', + pickup_sla='pickup_sla_value', + instore_product_location='instore_product_location_value', + )) + response = await client.insert_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = localinventory.InsertLocalInventoryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, localinventory.LocalInventory) + assert response.name == 'name_value' + assert response.account == 749 + assert response.store_code == 'store_code_value' + assert response.availability == 'availability_value' + assert response.quantity == 895 + assert response.pickup_method == 'pickup_method_value' + assert response.pickup_sla == 'pickup_sla_value' + assert response.instore_product_location == 'instore_product_location_value' + + +@pytest.mark.asyncio +async def test_insert_local_inventory_async_from_dict(): + await test_insert_local_inventory_async(request_type=dict) + +def test_insert_local_inventory_field_headers(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = localinventory.InsertLocalInventoryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_local_inventory), + '__call__') as call: + call.return_value = localinventory.LocalInventory() + client.insert_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_insert_local_inventory_field_headers_async(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = localinventory.InsertLocalInventoryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_local_inventory), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.LocalInventory()) + await client.insert_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + localinventory.DeleteLocalInventoryRequest, + dict, +]) +def test_delete_local_inventory(request_type, transport: str = 'grpc'): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = localinventory.DeleteLocalInventoryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_local_inventory_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = localinventory.DeleteLocalInventoryRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_local_inventory(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == localinventory.DeleteLocalInventoryRequest( + name='name_value', + ) + +def test_delete_local_inventory_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_local_inventory in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_local_inventory] = mock_rpc + request = {} + client.delete_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_local_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_local_inventory_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_local_inventory 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_local_inventory] = mock_rpc + + request = {} + await client.delete_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_local_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_local_inventory_async(transport: str = 'grpc_asyncio', request_type=localinventory.DeleteLocalInventoryRequest): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = localinventory.DeleteLocalInventoryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_local_inventory_async_from_dict(): + await test_delete_local_inventory_async(request_type=dict) + +def test_delete_local_inventory_field_headers(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = localinventory.DeleteLocalInventoryRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__call__') as call: + call.return_value = None + client.delete_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_local_inventory_field_headers_async(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = localinventory.DeleteLocalInventoryRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_local_inventory_flattened(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__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_local_inventory( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_local_inventory_flattened_error(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_local_inventory( + localinventory.DeleteLocalInventoryRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_local_inventory_flattened_async(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_local_inventory( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_local_inventory_flattened_error_async(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_local_inventory( + localinventory.DeleteLocalInventoryRequest(), + name='name_value', + ) + + +def test_list_local_inventories_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_local_inventories in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_local_inventories] = mock_rpc + + request = {} + client.list_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_local_inventories(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_local_inventories_rest_required_fields(request_type=localinventory.ListLocalInventoriesRequest): + transport_class = transports.LocalInventoryServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_local_inventories._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_local_inventories._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", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = localinventory.ListLocalInventoriesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = localinventory.ListLocalInventoriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_local_inventories(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_local_inventories_rest_unset_required_fields(): + transport = transports.LocalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_local_inventories._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_local_inventories_rest_flattened(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = localinventory.ListLocalInventoriesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1/products/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = localinventory.ListLocalInventoriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_local_inventories(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/inventories/v1beta/{parent=accounts/*/products/*}/localInventories" % client.transport._host, args[1]) + + +def test_list_local_inventories_rest_flattened_error(transport: str = 'rest'): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_local_inventories( + localinventory.ListLocalInventoriesRequest(), + parent='parent_value', + ) + + +def test_list_local_inventories_rest_pager(transport: str = 'rest'): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + next_page_token='abc', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[], + next_page_token='def', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + ], + next_page_token='ghi', + ), + localinventory.ListLocalInventoriesResponse( + local_inventories=[ + localinventory.LocalInventory(), + localinventory.LocalInventory(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(localinventory.ListLocalInventoriesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'accounts/sample1/products/sample2'} + + pager = client.list_local_inventories(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, localinventory.LocalInventory) + for i in results) + + pages = list(client.list_local_inventories(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_insert_local_inventory_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.insert_local_inventory in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.insert_local_inventory] = mock_rpc + + request = {} + client.insert_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.insert_local_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_insert_local_inventory_rest_required_fields(request_type=localinventory.InsertLocalInventoryRequest): + transport_class = transports.LocalInventoryServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).insert_local_inventory._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).insert_local_inventory._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = localinventory.LocalInventory() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = localinventory.LocalInventory.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.insert_local_inventory(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_insert_local_inventory_rest_unset_required_fields(): + transport = transports.LocalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.insert_local_inventory._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "localInventory", ))) + + +def test_delete_local_inventory_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_local_inventory in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_local_inventory] = mock_rpc + + request = {} + client.delete_local_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_local_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_local_inventory_rest_required_fields(request_type=localinventory.DeleteLocalInventoryRequest): + transport_class = transports.LocalInventoryServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_local_inventory._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_local_inventory._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_local_inventory(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_local_inventory_rest_unset_required_fields(): + transport = transports.LocalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_local_inventory._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_local_inventory_rest_flattened(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/products/sample2/localInventories/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_local_inventory(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/inventories/v1beta/{name=accounts/*/products/*/localInventories/*}" % client.transport._host, args[1]) + + +def test_delete_local_inventory_rest_flattened_error(transport: str = 'rest'): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_local_inventory( + localinventory.DeleteLocalInventoryRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.LocalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.LocalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LocalInventoryServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.LocalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = LocalInventoryServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = LocalInventoryServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.LocalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LocalInventoryServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.LocalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = LocalInventoryServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.LocalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.LocalInventoryServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.LocalInventoryServiceGrpcTransport, + transports.LocalInventoryServiceGrpcAsyncIOTransport, + transports.LocalInventoryServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_kind_grpc(): + transport = LocalInventoryServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_local_inventories_empty_call_grpc(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + call.return_value = localinventory.ListLocalInventoriesResponse() + client.list_local_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = localinventory.ListLocalInventoriesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_insert_local_inventory_empty_call_grpc(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_local_inventory), + '__call__') as call: + call.return_value = localinventory.LocalInventory() + client.insert_local_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = localinventory.InsertLocalInventoryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_local_inventory_empty_call_grpc(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__call__') as call: + call.return_value = None + client.delete_local_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = localinventory.DeleteLocalInventoryRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = LocalInventoryServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_local_inventories_empty_call_grpc_asyncio(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.ListLocalInventoriesResponse( + next_page_token='next_page_token_value', + )) + await client.list_local_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = localinventory.ListLocalInventoriesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_insert_local_inventory_empty_call_grpc_asyncio(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_local_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.LocalInventory( + name='name_value', + account=749, + store_code='store_code_value', + availability='availability_value', + quantity=895, + pickup_method='pickup_method_value', + pickup_sla='pickup_sla_value', + instore_product_location='instore_product_location_value', + )) + await client.insert_local_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = localinventory.InsertLocalInventoryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_local_inventory_empty_call_grpc_asyncio(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_local_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = localinventory.DeleteLocalInventoryRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = LocalInventoryServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_local_inventories_rest_bad_request(request_type=localinventory.ListLocalInventoriesRequest): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/products/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_local_inventories(request) + + +@pytest.mark.parametrize("request_type", [ + localinventory.ListLocalInventoriesRequest, + dict, +]) +def test_list_local_inventories_rest_call_success(request_type): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/products/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = localinventory.ListLocalInventoriesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = localinventory.ListLocalInventoriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_local_inventories(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListLocalInventoriesPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_local_inventories_rest_interceptors(null_interceptor): + transport = transports.LocalInventoryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LocalInventoryServiceRestInterceptor(), + ) + client = LocalInventoryServiceClient(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.LocalInventoryServiceRestInterceptor, "post_list_local_inventories") as post, \ + mock.patch.object(transports.LocalInventoryServiceRestInterceptor, "post_list_local_inventories_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.LocalInventoryServiceRestInterceptor, "pre_list_local_inventories") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = localinventory.ListLocalInventoriesRequest.pb(localinventory.ListLocalInventoriesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = localinventory.ListLocalInventoriesResponse.to_json(localinventory.ListLocalInventoriesResponse()) + req.return_value.content = return_value + + request = localinventory.ListLocalInventoriesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = localinventory.ListLocalInventoriesResponse() + post_with_metadata.return_value = localinventory.ListLocalInventoriesResponse(), metadata + + client.list_local_inventories(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_insert_local_inventory_rest_bad_request(request_type=localinventory.InsertLocalInventoryRequest): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/products/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.insert_local_inventory(request) + + +@pytest.mark.parametrize("request_type", [ + localinventory.InsertLocalInventoryRequest, + dict, +]) +def test_insert_local_inventory_rest_call_success(request_type): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/products/sample2'} + request_init["local_inventory"] = {'name': 'name_value', 'account': 749, 'store_code': 'store_code_value', 'price': {'amount_micros': 1408, 'currency_code': 'currency_code_value'}, 'sale_price': {}, 'sale_price_effective_date': {'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}}, 'availability': 'availability_value', 'quantity': 895, 'pickup_method': 'pickup_method_value', 'pickup_sla': 'pickup_sla_value', 'instore_product_location': 'instore_product_location_value', 'custom_attributes': [{'name': 'name_value', 'value': 'value_value', 'group_values': {}}]} + # 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 = localinventory.InsertLocalInventoryRequest.meta.fields["local_inventory"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["local_inventory"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["local_inventory"][field])): + del request_init["local_inventory"][field][i][subfield] + else: + del request_init["local_inventory"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = localinventory.LocalInventory( + name='name_value', + account=749, + store_code='store_code_value', + availability='availability_value', + quantity=895, + pickup_method='pickup_method_value', + pickup_sla='pickup_sla_value', + instore_product_location='instore_product_location_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = localinventory.LocalInventory.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.insert_local_inventory(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, localinventory.LocalInventory) + assert response.name == 'name_value' + assert response.account == 749 + assert response.store_code == 'store_code_value' + assert response.availability == 'availability_value' + assert response.quantity == 895 + assert response.pickup_method == 'pickup_method_value' + assert response.pickup_sla == 'pickup_sla_value' + assert response.instore_product_location == 'instore_product_location_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_insert_local_inventory_rest_interceptors(null_interceptor): + transport = transports.LocalInventoryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LocalInventoryServiceRestInterceptor(), + ) + client = LocalInventoryServiceClient(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.LocalInventoryServiceRestInterceptor, "post_insert_local_inventory") as post, \ + mock.patch.object(transports.LocalInventoryServiceRestInterceptor, "post_insert_local_inventory_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.LocalInventoryServiceRestInterceptor, "pre_insert_local_inventory") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = localinventory.InsertLocalInventoryRequest.pb(localinventory.InsertLocalInventoryRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = localinventory.LocalInventory.to_json(localinventory.LocalInventory()) + req.return_value.content = return_value + + request = localinventory.InsertLocalInventoryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = localinventory.LocalInventory() + post_with_metadata.return_value = localinventory.LocalInventory(), metadata + + client.insert_local_inventory(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_local_inventory_rest_bad_request(request_type=localinventory.DeleteLocalInventoryRequest): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/products/sample2/localInventories/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_local_inventory(request) + + +@pytest.mark.parametrize("request_type", [ + localinventory.DeleteLocalInventoryRequest, + dict, +]) +def test_delete_local_inventory_rest_call_success(request_type): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/products/sample2/localInventories/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = '' + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_local_inventory(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_local_inventory_rest_interceptors(null_interceptor): + transport = transports.LocalInventoryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LocalInventoryServiceRestInterceptor(), + ) + client = LocalInventoryServiceClient(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.LocalInventoryServiceRestInterceptor, "pre_delete_local_inventory") as pre: + pre.assert_not_called() + pb_message = localinventory.DeleteLocalInventoryRequest.pb(localinventory.DeleteLocalInventoryRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = localinventory.DeleteLocalInventoryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_local_inventory(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + +def test_initialize_client_w_rest(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_local_inventories_empty_call_rest(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_local_inventories), + '__call__') as call: + client.list_local_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = localinventory.ListLocalInventoriesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_insert_local_inventory_empty_call_rest(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_local_inventory), + '__call__') as call: + client.insert_local_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = localinventory.InsertLocalInventoryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_local_inventory_empty_call_rest(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_local_inventory), + '__call__') as call: + client.delete_local_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = localinventory.DeleteLocalInventoryRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.LocalInventoryServiceGrpcTransport, + ) + +def test_local_inventory_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.LocalInventoryServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_local_inventory_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_inventories_v1beta.services.local_inventory_service.transports.LocalInventoryServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.LocalInventoryServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_local_inventories', + 'insert_local_inventory', + 'delete_local_inventory', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_local_inventory_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.shopping.merchant_inventories_v1beta.services.local_inventory_service.transports.LocalInventoryServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LocalInventoryServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/content', +), + quota_project_id="octopus", + ) + + +def test_local_inventory_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.shopping.merchant_inventories_v1beta.services.local_inventory_service.transports.LocalInventoryServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LocalInventoryServiceTransport() + adc.assert_called_once() + + +def test_local_inventory_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + LocalInventoryServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/content', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.LocalInventoryServiceGrpcTransport, + transports.LocalInventoryServiceGrpcAsyncIOTransport, + ], +) +def test_local_inventory_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/content',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.LocalInventoryServiceGrpcTransport, + transports.LocalInventoryServiceGrpcAsyncIOTransport, + transports.LocalInventoryServiceRestTransport, + ], +) +def test_local_inventory_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.LocalInventoryServiceGrpcTransport, grpc_helpers), + (transports.LocalInventoryServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_local_inventory_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "merchantapi.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/content', +), + scopes=["1", "2"], + default_host="merchantapi.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.LocalInventoryServiceGrpcTransport, transports.LocalInventoryServiceGrpcAsyncIOTransport]) +def test_local_inventory_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_local_inventory_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.LocalInventoryServiceRestTransport ( + 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", +]) +def test_local_inventory_service_host_no_port(transport_name): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='merchantapi.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'merchantapi.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://merchantapi.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_local_inventory_service_host_with_port(transport_name): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='merchantapi.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'merchantapi.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://merchantapi.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_local_inventory_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = LocalInventoryServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = LocalInventoryServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_local_inventories._session + session2 = client2.transport.list_local_inventories._session + assert session1 != session2 + session1 = client1.transport.insert_local_inventory._session + session2 = client2.transport.insert_local_inventory._session + assert session1 != session2 + session1 = client1.transport.delete_local_inventory._session + session2 = client2.transport.delete_local_inventory._session + assert session1 != session2 +def test_local_inventory_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.LocalInventoryServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_local_inventory_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.LocalInventoryServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.LocalInventoryServiceGrpcTransport, transports.LocalInventoryServiceGrpcAsyncIOTransport]) +def test_local_inventory_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.LocalInventoryServiceGrpcTransport, transports.LocalInventoryServiceGrpcAsyncIOTransport]) +def test_local_inventory_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_local_inventory_path(): + account = "squid" + product = "clam" + store_code = "whelk" + expected = "accounts/{account}/products/{product}/localInventories/{store_code}".format(account=account, product=product, store_code=store_code, ) + actual = LocalInventoryServiceClient.local_inventory_path(account, product, store_code) + assert expected == actual + + +def test_parse_local_inventory_path(): + expected = { + "account": "octopus", + "product": "oyster", + "store_code": "nudibranch", + } + path = LocalInventoryServiceClient.local_inventory_path(**expected) + + # Check that the path construction is reversible. + actual = LocalInventoryServiceClient.parse_local_inventory_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = LocalInventoryServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = LocalInventoryServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = LocalInventoryServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = LocalInventoryServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = LocalInventoryServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = LocalInventoryServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = LocalInventoryServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = LocalInventoryServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = LocalInventoryServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = LocalInventoryServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = LocalInventoryServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = LocalInventoryServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = LocalInventoryServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = LocalInventoryServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = LocalInventoryServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.LocalInventoryServiceTransport, '_prep_wrapped_messages') as prep: + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.LocalInventoryServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = LocalInventoryServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_transport_close_grpc(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = LocalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = LocalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport), + (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + 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=None, + ) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_regional_inventory_service.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_regional_inventory_service.py new file mode 100644 index 000000000000..a9aec23ea1e3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_regional_inventory_service.py @@ -0,0 +1,3638 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +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 proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +try: + from google.auth.aio import credentials as ga_credentials_async + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import 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 +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +from google.protobuf import timestamp_pb2 # type: ignore +from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service import RegionalInventoryServiceAsyncClient +from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service import RegionalInventoryServiceClient +from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service import pagers +from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service import transports +from google.shopping.merchant_inventories_v1beta.types import regionalinventory +from google.shopping.type.types import types +from google.type import interval_pb2 # type: ignore +import google.auth + + + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + +# 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 + +# 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 + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert RegionalInventoryServiceClient._get_default_mtls_endpoint(None) is None + assert RegionalInventoryServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert RegionalInventoryServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert RegionalInventoryServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert RegionalInventoryServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert RegionalInventoryServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert RegionalInventoryServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert RegionalInventoryServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert RegionalInventoryServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + RegionalInventoryServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert RegionalInventoryServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert RegionalInventoryServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert RegionalInventoryServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + RegionalInventoryServiceClient._read_environment_variables() + 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 RegionalInventoryServiceClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert RegionalInventoryServiceClient._get_client_cert_source(None, False) is None + assert RegionalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert RegionalInventoryServiceClient._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 RegionalInventoryServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert RegionalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(RegionalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceClient)) +@mock.patch.object(RegionalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = RegionalInventoryServiceClient._DEFAULT_UNIVERSE + default_endpoint = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert RegionalInventoryServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert RegionalInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + assert RegionalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert RegionalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "always") == RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + assert RegionalInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + assert RegionalInventoryServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert RegionalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + RegionalInventoryServiceClient._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 RegionalInventoryServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert RegionalInventoryServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert RegionalInventoryServiceClient._get_universe_domain(None, None) == RegionalInventoryServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + RegionalInventoryServiceClient._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) +]) +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) + client = RegionalInventoryServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + +@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") + client = RegionalInventoryServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + +@pytest.mark.parametrize("client_class,transport_name", [ + (RegionalInventoryServiceClient, "grpc"), + (RegionalInventoryServiceAsyncClient, "grpc_asyncio"), + (RegionalInventoryServiceClient, "rest"), +]) +def test_regional_inventory_service_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: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'merchantapi.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://merchantapi.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.RegionalInventoryServiceGrpcTransport, "grpc"), + (transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.RegionalInventoryServiceRestTransport, "rest"), +]) +def test_regional_inventory_service_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: + 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", [ + (RegionalInventoryServiceClient, "grpc"), + (RegionalInventoryServiceAsyncClient, "grpc_asyncio"), + (RegionalInventoryServiceClient, "rest"), +]) +def test_regional_inventory_service_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: + factory.return_value = creds + 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) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'merchantapi.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://merchantapi.googleapis.com' + ) + + +def test_regional_inventory_service_client_get_transport_class(): + transport = RegionalInventoryServiceClient.get_transport_class() + available_transports = [ + transports.RegionalInventoryServiceGrpcTransport, + transports.RegionalInventoryServiceRestTransport, + ] + assert transport in available_transports + + transport = RegionalInventoryServiceClient.get_transport_class("grpc") + assert transport == transports.RegionalInventoryServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc"), + (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest"), +]) +@mock.patch.object(RegionalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceClient)) +@mock.patch.object(RegionalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceAsyncClient)) +def test_regional_inventory_service_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(RegionalInventoryServiceClient, '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(RegionalInventoryServiceClient, '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: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + 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=None, + ) + + # 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: + 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), + 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=None, + ) + + # 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: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + 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=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) 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`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + 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: + 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), + 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", [ + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc", "true"), + (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc", "false"), + (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest", "true"), + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(RegionalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceClient)) +@mock.patch.object(RegionalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_regional_inventory_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, 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) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # 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): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # 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): + 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), + 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=None, + ) + + +@pytest.mark.parametrize("client_class", [ + RegionalInventoryServiceClient, RegionalInventoryServiceAsyncClient +]) +@mock.patch.object(RegionalInventoryServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegionalInventoryServiceClient)) +@mock.patch.object(RegionalInventoryServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegionalInventoryServiceAsyncClient)) +def test_regional_inventory_service_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) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + 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) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + 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 "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # 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): + 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() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) 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`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + RegionalInventoryServiceClient, RegionalInventoryServiceAsyncClient +]) +@mock.patch.object(RegionalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceClient)) +@mock.patch.object(RegionalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceAsyncClient)) +def test_regional_inventory_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = RegionalInventoryServiceClient._DEFAULT_UNIVERSE + default_endpoint = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = RegionalInventoryServiceClient._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()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + 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()) + 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) + + # 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. + options = client_options.ClientOptions() + 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()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc"), + (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest"), +]) +def test_regional_inventory_service_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: + 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), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc", grpc_helpers), + (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest", None), +]) +def test_regional_inventory_service_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" + ) + + 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), + 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=None, + ) + +def test_regional_inventory_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.transports.RegionalInventoryServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = RegionalInventoryServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + 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=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc", grpc_helpers), + (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_regional_inventory_service_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" + ) + + 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), + 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=None, + ) + + # 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: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "merchantapi.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/content', +), + scopes=None, + default_host="merchantapi.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + regionalinventory.ListRegionalInventoriesRequest, + dict, +]) +def test_list_regional_inventories(request_type, transport: str = 'grpc'): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regionalinventory.ListRegionalInventoriesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_regional_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = regionalinventory.ListRegionalInventoriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRegionalInventoriesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_regional_inventories_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = regionalinventory.ListRegionalInventoriesRequest( + 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_regional_inventories), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_regional_inventories(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == regionalinventory.ListRegionalInventoriesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_regional_inventories_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_regional_inventories in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_regional_inventories] = mock_rpc + request = {} + client.list_regional_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_regional_inventories(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_regional_inventories_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_regional_inventories 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_regional_inventories] = mock_rpc + + request = {} + await client.list_regional_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_regional_inventories(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_regional_inventories_async(transport: str = 'grpc_asyncio', request_type=regionalinventory.ListRegionalInventoriesRequest): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.ListRegionalInventoriesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_regional_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = regionalinventory.ListRegionalInventoriesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRegionalInventoriesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_regional_inventories_async_from_dict(): + await test_list_regional_inventories_async(request_type=dict) + +def test_list_regional_inventories_field_headers(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = regionalinventory.ListRegionalInventoriesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + call.return_value = regionalinventory.ListRegionalInventoriesResponse() + client.list_regional_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_regional_inventories_field_headers_async(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = regionalinventory.ListRegionalInventoriesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.ListRegionalInventoriesResponse()) + await client.list_regional_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_regional_inventories_flattened(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regionalinventory.ListRegionalInventoriesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_regional_inventories( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_regional_inventories_flattened_error(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_regional_inventories( + regionalinventory.ListRegionalInventoriesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_regional_inventories_flattened_async(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regionalinventory.ListRegionalInventoriesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.ListRegionalInventoriesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_regional_inventories( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_regional_inventories_flattened_error_async(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_regional_inventories( + regionalinventory.ListRegionalInventoriesRequest(), + parent='parent_value', + ) + + +def test_list_regional_inventories_pager(transport_name: str = "grpc"): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + next_page_token='abc', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[], + next_page_token='def', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + ], + next_page_token='ghi', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_regional_inventories(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, regionalinventory.RegionalInventory) + for i in results) +def test_list_regional_inventories_pages(transport_name: str = "grpc"): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + next_page_token='abc', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[], + next_page_token='def', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + ], + next_page_token='ghi', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + ), + RuntimeError, + ) + pages = list(client.list_regional_inventories(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_regional_inventories_async_pager(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + next_page_token='abc', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[], + next_page_token='def', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + ], + next_page_token='ghi', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_regional_inventories(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, regionalinventory.RegionalInventory) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_regional_inventories_async_pages(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + next_page_token='abc', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[], + next_page_token='def', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + ], + next_page_token='ghi', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_regional_inventories(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + regionalinventory.InsertRegionalInventoryRequest, + dict, +]) +def test_insert_regional_inventory(request_type, transport: str = 'grpc'): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_regional_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regionalinventory.RegionalInventory( + name='name_value', + account=749, + region='region_value', + availability='availability_value', + ) + response = client.insert_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = regionalinventory.InsertRegionalInventoryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, regionalinventory.RegionalInventory) + assert response.name == 'name_value' + assert response.account == 749 + assert response.region == 'region_value' + assert response.availability == 'availability_value' + + +def test_insert_regional_inventory_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = regionalinventory.InsertRegionalInventoryRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_regional_inventory), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.insert_regional_inventory(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == regionalinventory.InsertRegionalInventoryRequest( + parent='parent_value', + ) + +def test_insert_regional_inventory_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.insert_regional_inventory in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.insert_regional_inventory] = mock_rpc + request = {} + client.insert_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.insert_regional_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_insert_regional_inventory_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.insert_regional_inventory 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.insert_regional_inventory] = mock_rpc + + request = {} + await client.insert_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.insert_regional_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_insert_regional_inventory_async(transport: str = 'grpc_asyncio', request_type=regionalinventory.InsertRegionalInventoryRequest): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_regional_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.RegionalInventory( + name='name_value', + account=749, + region='region_value', + availability='availability_value', + )) + response = await client.insert_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = regionalinventory.InsertRegionalInventoryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, regionalinventory.RegionalInventory) + assert response.name == 'name_value' + assert response.account == 749 + assert response.region == 'region_value' + assert response.availability == 'availability_value' + + +@pytest.mark.asyncio +async def test_insert_regional_inventory_async_from_dict(): + await test_insert_regional_inventory_async(request_type=dict) + +def test_insert_regional_inventory_field_headers(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = regionalinventory.InsertRegionalInventoryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_regional_inventory), + '__call__') as call: + call.return_value = regionalinventory.RegionalInventory() + client.insert_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_insert_regional_inventory_field_headers_async(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = regionalinventory.InsertRegionalInventoryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_regional_inventory), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.RegionalInventory()) + await client.insert_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + regionalinventory.DeleteRegionalInventoryRequest, + dict, +]) +def test_delete_regional_inventory(request_type, transport: str = 'grpc'): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = regionalinventory.DeleteRegionalInventoryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_regional_inventory_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = regionalinventory.DeleteRegionalInventoryRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_regional_inventory(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == regionalinventory.DeleteRegionalInventoryRequest( + name='name_value', + ) + +def test_delete_regional_inventory_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_regional_inventory in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_regional_inventory] = mock_rpc + request = {} + client.delete_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_regional_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_regional_inventory_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_regional_inventory 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_regional_inventory] = mock_rpc + + request = {} + await client.delete_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_regional_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_regional_inventory_async(transport: str = 'grpc_asyncio', request_type=regionalinventory.DeleteRegionalInventoryRequest): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = regionalinventory.DeleteRegionalInventoryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_regional_inventory_async_from_dict(): + await test_delete_regional_inventory_async(request_type=dict) + +def test_delete_regional_inventory_field_headers(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = regionalinventory.DeleteRegionalInventoryRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__call__') as call: + call.return_value = None + client.delete_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_regional_inventory_field_headers_async(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = regionalinventory.DeleteRegionalInventoryRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_regional_inventory_flattened(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__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_regional_inventory( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_regional_inventory_flattened_error(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_regional_inventory( + regionalinventory.DeleteRegionalInventoryRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_regional_inventory_flattened_async(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_regional_inventory( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_regional_inventory_flattened_error_async(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_regional_inventory( + regionalinventory.DeleteRegionalInventoryRequest(), + name='name_value', + ) + + +def test_list_regional_inventories_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_regional_inventories in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_regional_inventories] = mock_rpc + + request = {} + client.list_regional_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_regional_inventories(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_regional_inventories_rest_required_fields(request_type=regionalinventory.ListRegionalInventoriesRequest): + transport_class = transports.RegionalInventoryServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_regional_inventories._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_regional_inventories._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", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = regionalinventory.ListRegionalInventoriesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = regionalinventory.ListRegionalInventoriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_regional_inventories(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_regional_inventories_rest_unset_required_fields(): + transport = transports.RegionalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_regional_inventories._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_regional_inventories_rest_flattened(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = regionalinventory.ListRegionalInventoriesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1/products/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = regionalinventory.ListRegionalInventoriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_regional_inventories(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/inventories/v1beta/{parent=accounts/*/products/*}/regionalInventories" % client.transport._host, args[1]) + + +def test_list_regional_inventories_rest_flattened_error(transport: str = 'rest'): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_regional_inventories( + regionalinventory.ListRegionalInventoriesRequest(), + parent='parent_value', + ) + + +def test_list_regional_inventories_rest_pager(transport: str = 'rest'): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + next_page_token='abc', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[], + next_page_token='def', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + ], + next_page_token='ghi', + ), + regionalinventory.ListRegionalInventoriesResponse( + regional_inventories=[ + regionalinventory.RegionalInventory(), + regionalinventory.RegionalInventory(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(regionalinventory.ListRegionalInventoriesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'accounts/sample1/products/sample2'} + + pager = client.list_regional_inventories(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, regionalinventory.RegionalInventory) + for i in results) + + pages = list(client.list_regional_inventories(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_insert_regional_inventory_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.insert_regional_inventory in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.insert_regional_inventory] = mock_rpc + + request = {} + client.insert_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.insert_regional_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_insert_regional_inventory_rest_required_fields(request_type=regionalinventory.InsertRegionalInventoryRequest): + transport_class = transports.RegionalInventoryServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).insert_regional_inventory._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).insert_regional_inventory._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = regionalinventory.RegionalInventory() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = regionalinventory.RegionalInventory.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.insert_regional_inventory(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_insert_regional_inventory_rest_unset_required_fields(): + transport = transports.RegionalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.insert_regional_inventory._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "regionalInventory", ))) + + +def test_delete_regional_inventory_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_regional_inventory in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_regional_inventory] = mock_rpc + + request = {} + client.delete_regional_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_regional_inventory(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_regional_inventory_rest_required_fields(request_type=regionalinventory.DeleteRegionalInventoryRequest): + transport_class = transports.RegionalInventoryServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_regional_inventory._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_regional_inventory._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_regional_inventory(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_regional_inventory_rest_unset_required_fields(): + transport = transports.RegionalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_regional_inventory._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_regional_inventory_rest_flattened(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/products/sample2/regionalInventories/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_regional_inventory(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/inventories/v1beta/{name=accounts/*/products/*/regionalInventories/*}" % client.transport._host, args[1]) + + +def test_delete_regional_inventory_rest_flattened_error(transport: str = 'rest'): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_regional_inventory( + regionalinventory.DeleteRegionalInventoryRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RegionalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RegionalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionalInventoryServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RegionalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RegionalInventoryServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RegionalInventoryServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RegionalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionalInventoryServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RegionalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RegionalInventoryServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.RegionalInventoryServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.RegionalInventoryServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.RegionalInventoryServiceGrpcTransport, + transports.RegionalInventoryServiceGrpcAsyncIOTransport, + transports.RegionalInventoryServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_kind_grpc(): + transport = RegionalInventoryServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_regional_inventories_empty_call_grpc(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + call.return_value = regionalinventory.ListRegionalInventoriesResponse() + client.list_regional_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regionalinventory.ListRegionalInventoriesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_insert_regional_inventory_empty_call_grpc(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_regional_inventory), + '__call__') as call: + call.return_value = regionalinventory.RegionalInventory() + client.insert_regional_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regionalinventory.InsertRegionalInventoryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_regional_inventory_empty_call_grpc(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__call__') as call: + call.return_value = None + client.delete_regional_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regionalinventory.DeleteRegionalInventoryRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = RegionalInventoryServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_regional_inventories_empty_call_grpc_asyncio(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.ListRegionalInventoriesResponse( + next_page_token='next_page_token_value', + )) + await client.list_regional_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regionalinventory.ListRegionalInventoriesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_insert_regional_inventory_empty_call_grpc_asyncio(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_regional_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.RegionalInventory( + name='name_value', + account=749, + region='region_value', + availability='availability_value', + )) + await client.insert_regional_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regionalinventory.InsertRegionalInventoryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_regional_inventory_empty_call_grpc_asyncio(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_regional_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regionalinventory.DeleteRegionalInventoryRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = RegionalInventoryServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_regional_inventories_rest_bad_request(request_type=regionalinventory.ListRegionalInventoriesRequest): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/products/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_regional_inventories(request) + + +@pytest.mark.parametrize("request_type", [ + regionalinventory.ListRegionalInventoriesRequest, + dict, +]) +def test_list_regional_inventories_rest_call_success(request_type): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/products/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = regionalinventory.ListRegionalInventoriesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = regionalinventory.ListRegionalInventoriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_regional_inventories(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRegionalInventoriesPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_regional_inventories_rest_interceptors(null_interceptor): + transport = transports.RegionalInventoryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegionalInventoryServiceRestInterceptor(), + ) + client = RegionalInventoryServiceClient(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.RegionalInventoryServiceRestInterceptor, "post_list_regional_inventories") as post, \ + mock.patch.object(transports.RegionalInventoryServiceRestInterceptor, "post_list_regional_inventories_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.RegionalInventoryServiceRestInterceptor, "pre_list_regional_inventories") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = regionalinventory.ListRegionalInventoriesRequest.pb(regionalinventory.ListRegionalInventoriesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = regionalinventory.ListRegionalInventoriesResponse.to_json(regionalinventory.ListRegionalInventoriesResponse()) + req.return_value.content = return_value + + request = regionalinventory.ListRegionalInventoriesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = regionalinventory.ListRegionalInventoriesResponse() + post_with_metadata.return_value = regionalinventory.ListRegionalInventoriesResponse(), metadata + + client.list_regional_inventories(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_insert_regional_inventory_rest_bad_request(request_type=regionalinventory.InsertRegionalInventoryRequest): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/products/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.insert_regional_inventory(request) + + +@pytest.mark.parametrize("request_type", [ + regionalinventory.InsertRegionalInventoryRequest, + dict, +]) +def test_insert_regional_inventory_rest_call_success(request_type): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/products/sample2'} + request_init["regional_inventory"] = {'name': 'name_value', 'account': 749, 'region': 'region_value', 'price': {'amount_micros': 1408, 'currency_code': 'currency_code_value'}, 'sale_price': {}, 'sale_price_effective_date': {'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}}, 'availability': 'availability_value', 'custom_attributes': [{'name': 'name_value', 'value': 'value_value', 'group_values': {}}]} + # 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 = regionalinventory.InsertRegionalInventoryRequest.meta.fields["regional_inventory"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["regional_inventory"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["regional_inventory"][field])): + del request_init["regional_inventory"][field][i][subfield] + else: + del request_init["regional_inventory"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = regionalinventory.RegionalInventory( + name='name_value', + account=749, + region='region_value', + availability='availability_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = regionalinventory.RegionalInventory.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.insert_regional_inventory(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, regionalinventory.RegionalInventory) + assert response.name == 'name_value' + assert response.account == 749 + assert response.region == 'region_value' + assert response.availability == 'availability_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_insert_regional_inventory_rest_interceptors(null_interceptor): + transport = transports.RegionalInventoryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegionalInventoryServiceRestInterceptor(), + ) + client = RegionalInventoryServiceClient(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.RegionalInventoryServiceRestInterceptor, "post_insert_regional_inventory") as post, \ + mock.patch.object(transports.RegionalInventoryServiceRestInterceptor, "post_insert_regional_inventory_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.RegionalInventoryServiceRestInterceptor, "pre_insert_regional_inventory") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = regionalinventory.InsertRegionalInventoryRequest.pb(regionalinventory.InsertRegionalInventoryRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = regionalinventory.RegionalInventory.to_json(regionalinventory.RegionalInventory()) + req.return_value.content = return_value + + request = regionalinventory.InsertRegionalInventoryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = regionalinventory.RegionalInventory() + post_with_metadata.return_value = regionalinventory.RegionalInventory(), metadata + + client.insert_regional_inventory(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_regional_inventory_rest_bad_request(request_type=regionalinventory.DeleteRegionalInventoryRequest): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/products/sample2/regionalInventories/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_regional_inventory(request) + + +@pytest.mark.parametrize("request_type", [ + regionalinventory.DeleteRegionalInventoryRequest, + dict, +]) +def test_delete_regional_inventory_rest_call_success(request_type): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/products/sample2/regionalInventories/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = '' + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_regional_inventory(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_regional_inventory_rest_interceptors(null_interceptor): + transport = transports.RegionalInventoryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegionalInventoryServiceRestInterceptor(), + ) + client = RegionalInventoryServiceClient(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.RegionalInventoryServiceRestInterceptor, "pre_delete_regional_inventory") as pre: + pre.assert_not_called() + pb_message = regionalinventory.DeleteRegionalInventoryRequest.pb(regionalinventory.DeleteRegionalInventoryRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = regionalinventory.DeleteRegionalInventoryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_regional_inventory(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + +def test_initialize_client_w_rest(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_regional_inventories_empty_call_rest(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_regional_inventories), + '__call__') as call: + client.list_regional_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regionalinventory.ListRegionalInventoriesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_insert_regional_inventory_empty_call_rest(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_regional_inventory), + '__call__') as call: + client.insert_regional_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regionalinventory.InsertRegionalInventoryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_regional_inventory_empty_call_rest(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_regional_inventory), + '__call__') as call: + client.delete_regional_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regionalinventory.DeleteRegionalInventoryRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.RegionalInventoryServiceGrpcTransport, + ) + +def test_regional_inventory_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RegionalInventoryServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_regional_inventory_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.transports.RegionalInventoryServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.RegionalInventoryServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_regional_inventories', + 'insert_regional_inventory', + 'delete_regional_inventory', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_regional_inventory_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.transports.RegionalInventoryServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionalInventoryServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/content', +), + quota_project_id="octopus", + ) + + +def test_regional_inventory_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.transports.RegionalInventoryServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionalInventoryServiceTransport() + adc.assert_called_once() + + +def test_regional_inventory_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RegionalInventoryServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/content', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RegionalInventoryServiceGrpcTransport, + transports.RegionalInventoryServiceGrpcAsyncIOTransport, + ], +) +def test_regional_inventory_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/content',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RegionalInventoryServiceGrpcTransport, + transports.RegionalInventoryServiceGrpcAsyncIOTransport, + transports.RegionalInventoryServiceRestTransport, + ], +) +def test_regional_inventory_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.RegionalInventoryServiceGrpcTransport, grpc_helpers), + (transports.RegionalInventoryServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_regional_inventory_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "merchantapi.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/content', +), + scopes=["1", "2"], + default_host="merchantapi.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.RegionalInventoryServiceGrpcTransport, transports.RegionalInventoryServiceGrpcAsyncIOTransport]) +def test_regional_inventory_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_regional_inventory_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.RegionalInventoryServiceRestTransport ( + 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", +]) +def test_regional_inventory_service_host_no_port(transport_name): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='merchantapi.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'merchantapi.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://merchantapi.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_regional_inventory_service_host_with_port(transport_name): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='merchantapi.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'merchantapi.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://merchantapi.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_regional_inventory_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = RegionalInventoryServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = RegionalInventoryServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_regional_inventories._session + session2 = client2.transport.list_regional_inventories._session + assert session1 != session2 + session1 = client1.transport.insert_regional_inventory._session + session2 = client2.transport.insert_regional_inventory._session + assert session1 != session2 + session1 = client1.transport.delete_regional_inventory._session + session2 = client2.transport.delete_regional_inventory._session + assert session1 != session2 +def test_regional_inventory_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RegionalInventoryServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_regional_inventory_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RegionalInventoryServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.RegionalInventoryServiceGrpcTransport, transports.RegionalInventoryServiceGrpcAsyncIOTransport]) +def test_regional_inventory_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.RegionalInventoryServiceGrpcTransport, transports.RegionalInventoryServiceGrpcAsyncIOTransport]) +def test_regional_inventory_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_regional_inventory_path(): + account = "squid" + product = "clam" + region = "whelk" + expected = "accounts/{account}/products/{product}/regionalInventories/{region}".format(account=account, product=product, region=region, ) + actual = RegionalInventoryServiceClient.regional_inventory_path(account, product, region) + assert expected == actual + + +def test_parse_regional_inventory_path(): + expected = { + "account": "octopus", + "product": "oyster", + "region": "nudibranch", + } + path = RegionalInventoryServiceClient.regional_inventory_path(**expected) + + # Check that the path construction is reversible. + actual = RegionalInventoryServiceClient.parse_regional_inventory_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = RegionalInventoryServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = RegionalInventoryServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RegionalInventoryServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = RegionalInventoryServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = RegionalInventoryServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RegionalInventoryServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = RegionalInventoryServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = RegionalInventoryServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RegionalInventoryServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = RegionalInventoryServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = RegionalInventoryServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RegionalInventoryServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = RegionalInventoryServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = RegionalInventoryServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RegionalInventoryServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.RegionalInventoryServiceTransport, '_prep_wrapped_messages') as prep: + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.RegionalInventoryServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = RegionalInventoryServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_transport_close_grpc(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = RegionalInventoryServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = RegionalInventoryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport), + (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + 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=None, + ) From 25bc500eb4be25f2edc269ab32031eb0953054d7 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Mon, 4 Aug 2025 13:01:42 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20po?= =?UTF-8?q?st-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../v1/.coveragerc | 13 - .../v1/.flake8 | 34 - .../v1/LICENSE | 202 - .../v1/MANIFEST.in | 20 - .../v1/README.rst | 143 - .../v1/docs/_static/custom.css | 20 - .../v1/docs/_templates/layout.html | 50 - .../v1/docs/conf.py | 385 -- .../v1/docs/index.rst | 10 - .../v1/docs/multiprocessing.rst | 7 - .../shopping/merchant_inventories/__init__.py | 55 - .../merchant_inventories_v1/__init__.py | 56 - .../merchant_inventories_v1/gapic_version.py | 16 - .../shopping/merchant_inventories_v1/py.typed | 2 - .../transports/__init__.py | 38 - .../merchant_inventories_v1/types/__init__.py | 48 - .../v1/mypy.ini | 3 - .../v1/noxfile.py | 591 --- .../v1/setup.py | 99 - .../v1/testing/constraints-3.10.txt | 7 - .../v1/testing/constraints-3.11.txt | 7 - .../v1/testing/constraints-3.12.txt | 7 - .../v1/testing/constraints-3.13.txt | 12 - .../v1/testing/constraints-3.7.txt | 11 - .../v1/testing/constraints-3.8.txt | 7 - .../v1/testing/constraints-3.9.txt | 7 - .../v1/tests/__init__.py | 16 - .../v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../gapic/merchant_inventories_v1/__init__.py | 16 - .../v1beta/.coveragerc | 13 - .../v1beta/.flake8 | 34 - .../v1beta/LICENSE | 202 - .../v1beta/MANIFEST.in | 20 - .../v1beta/README.rst | 143 - .../v1beta/docs/_static/custom.css | 20 - .../v1beta/docs/_templates/layout.html | 50 - .../v1beta/docs/conf.py | 385 -- .../v1beta/docs/index.rst | 10 - .../local_inventory_service.rst | 10 - .../regional_inventory_service.rst | 10 - .../merchant_inventories_v1beta/services_.rst | 7 - .../merchant_inventories_v1beta/types_.rst | 6 - .../v1beta/docs/multiprocessing.rst | 7 - .../shopping/merchant_inventories/__init__.py | 51 - .../merchant_inventories/gapic_version.py | 16 - .../shopping/merchant_inventories/py.typed | 2 - .../merchant_inventories_v1beta/__init__.py | 52 - .../gapic_metadata.json | 137 - .../gapic_version.py | 16 - .../merchant_inventories_v1beta/py.typed | 2 - .../local_inventory_service/__init__.py | 22 - .../local_inventory_service/async_client.py | 591 --- .../local_inventory_service/client.py | 950 ----- .../local_inventory_service/pagers.py | 166 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 188 - .../transports/grpc.py | 418 -- .../transports/grpc_asyncio.py | 449 -- .../transports/rest.py | 640 --- .../transports/rest_base.py | 213 - .../regional_inventory_service/__init__.py | 22 - .../async_client.py | 597 --- .../regional_inventory_service/client.py | 956 ----- .../regional_inventory_service/pagers.py | 166 - .../transports/README.rst | 9 - .../transports/base.py | 188 - .../transports/grpc.py | 419 -- .../transports/grpc_asyncio.py | 450 -- .../transports/rest.py | 644 --- .../transports/rest_base.py | 213 - .../types/localinventory.py | 281 -- .../types/regionalinventory.py | 236 -- .../v1beta/mypy.ini | 3 - .../v1beta/noxfile.py | 591 --- ...ry_service_delete_local_inventory_async.py | 50 - ...ory_service_delete_local_inventory_sync.py | 50 - ...ry_service_insert_local_inventory_async.py | 56 - ...ory_service_insert_local_inventory_sync.py | 56 - ...ry_service_list_local_inventories_async.py | 53 - ...ory_service_list_local_inventories_sync.py | 53 - ...service_delete_regional_inventory_async.py | 50 - ..._service_delete_regional_inventory_sync.py | 50 - ...service_insert_regional_inventory_async.py | 56 - ..._service_insert_regional_inventory_sync.py | 56 - ...service_list_regional_inventories_async.py | 53 - ..._service_list_regional_inventories_sync.py | 53 - ....shopping.merchant.inventories.v1beta.json | 953 ----- ...up_merchant_inventories_v1beta_keywords.py | 181 - .../v1beta/setup.py | 99 - .../v1beta/testing/constraints-3.10.txt | 7 - .../v1beta/testing/constraints-3.11.txt | 7 - .../v1beta/testing/constraints-3.12.txt | 7 - .../v1beta/testing/constraints-3.13.txt | 12 - .../v1beta/testing/constraints-3.7.txt | 11 - .../v1beta/testing/constraints-3.8.txt | 7 - .../v1beta/testing/constraints-3.9.txt | 7 - .../v1beta/tests/__init__.py | 16 - .../v1beta/tests/unit/__init__.py | 16 - .../v1beta/tests/unit/gapic/__init__.py | 16 - .../merchant_inventories_v1beta/__init__.py | 16 - .../test_local_inventory_service.py | 3666 ----------------- .../test_regional_inventory_service.py | 3638 ---------------- .../docs/index.rst | 11 + .../local_inventory_service.rst | 0 .../regional_inventory_service.rst | 0 .../merchant_inventories_v1/services_.rst | 0 .../docs/merchant_inventories_v1/types_.rst | 0 .../merchant_inventories/gapic_version.py | 2 +- .../merchant_inventories_v1/__init__.py | 65 + .../gapic_metadata.json | 0 .../merchant_inventories_v1}/gapic_version.py | 0 .../merchant_inventories_v1}/py.typed | 0 .../services/__init__.py | 0 .../local_inventory_service/__init__.py | 6 +- .../local_inventory_service/async_client.py | 236 +- .../local_inventory_service/client.py | 387 +- .../local_inventory_service/pagers.py | 75 +- .../transports/README.rst | 0 .../transports/__init__.py | 27 +- .../transports/base.py | 121 +- .../transports/grpc.py | 137 +- .../transports/grpc_asyncio.py | 148 +- .../transports/rest.py | 424 +- .../transports/rest_base.py | 148 +- .../regional_inventory_service/__init__.py | 6 +- .../async_client.py | 244 +- .../regional_inventory_service/client.py | 403 +- .../regional_inventory_service/pagers.py | 81 +- .../transports/README.rst | 0 .../transports/__init__.py | 27 +- .../transports/base.py | 124 +- .../transports/grpc.py | 138 +- .../transports/grpc_asyncio.py | 148 +- .../transports/rest.py | 427 +- .../transports/rest_base.py | 148 +- .../types/__init__.py | 23 +- .../types/inventories_common.py | 12 +- .../types/localinventory.py | 31 +- .../types/regionalinventory.py | 31 +- .../gapic_version.py | 2 +- ...ry_service_delete_local_inventory_async.py | 0 ...ory_service_delete_local_inventory_sync.py | 0 ...ry_service_insert_local_inventory_async.py | 0 ...ory_service_insert_local_inventory_sync.py | 0 ...ry_service_list_local_inventories_async.py | 0 ...ory_service_list_local_inventories_sync.py | 0 ...service_delete_regional_inventory_async.py | 0 ..._service_delete_regional_inventory_sync.py | 0 ...service_insert_regional_inventory_async.py | 0 ..._service_insert_regional_inventory_sync.py | 0 ...service_list_regional_inventories_async.py | 0 ..._service_list_regional_inventories_sync.py | 0 ...ogle.shopping.merchant.inventories.v1.json | 0 ....shopping.merchant.inventories.v1beta.json | 2 +- .../fixup_merchant_inventories_v1_keywords.py | 0 .../merchant_inventories_v1}/__init__.py | 0 .../test_local_inventory_service.py | 2246 ++++++---- .../test_regional_inventory_service.py | 2284 ++++++---- 160 files changed, 5352 insertions(+), 23673 deletions(-) delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/.coveragerc delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/.flake8 delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/LICENSE delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/docs/_templates/layout.html delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/docs/multiprocessing.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/py.typed delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/mypy.ini delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/noxfile.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/setup.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/merchant_inventories_v1/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/.coveragerc delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/.flake8 delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/LICENSE delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/MANIFEST.in delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/_templates/layout.html delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/conf.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/index.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/local_inventory_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/regional_inventory_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/services_.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/types_.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/multiprocessing.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/gapic_version.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/py.typed delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_metadata.json delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_version.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/py.typed delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/pagers.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/pagers.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/localinventory.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/regionalinventory.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/mypy.ini delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/noxfile.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1beta.json delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/scripts/fixup_merchant_inventories_v1beta_keywords.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/setup.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_local_inventory_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_regional_inventory_service.py rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/docs/merchant_inventories_v1/local_inventory_service.rst (100%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/docs/merchant_inventories_v1/regional_inventory_service.rst (100%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/docs/merchant_inventories_v1/services_.rst (100%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/docs/merchant_inventories_v1/types_.rst (100%) create mode 100644 packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/__init__.py rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/google/shopping/merchant_inventories_v1/gapic_metadata.json (100%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories => packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1}/gapic_version.py (100%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories => packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1}/py.typed (100%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/google/shopping/merchant_inventories_v1/services/__init__.py (100%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/google/shopping/merchant_inventories_v1/services/local_inventory_service/__init__.py (90%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/google/shopping/merchant_inventories_v1/services/local_inventory_service/async_client.py (80%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/google/shopping/merchant_inventories_v1/services/local_inventory_service/client.py (79%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/google/shopping/merchant_inventories_v1/services/local_inventory_service/pagers.py (79%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/README.rst (100%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/__init__.py (59%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/base.py (67%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/grpc.py (84%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/grpc_asyncio.py (83%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/rest.py (69%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/rest_base.py (61%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/google/shopping/merchant_inventories_v1/services/regional_inventory_service/__init__.py (89%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/google/shopping/merchant_inventories_v1/services/regional_inventory_service/async_client.py (79%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/google/shopping/merchant_inventories_v1/services/regional_inventory_service/client.py (78%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/google/shopping/merchant_inventories_v1/services/regional_inventory_service/pagers.py (77%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/README.rst (100%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta => packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1}/services/regional_inventory_service/transports/__init__.py (59%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/base.py (66%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/grpc.py (83%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/grpc_asyncio.py (83%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/rest.py (70%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/rest_base.py (61%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta => packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1}/types/__init__.py (67%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/google/shopping/merchant_inventories_v1/types/inventories_common.py (98%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/google/shopping/merchant_inventories_v1/types/localinventory.py (91%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/google/shopping/merchant_inventories_v1/types/regionalinventory.py (90%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_delete_local_inventory_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_delete_local_inventory_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_insert_local_inventory_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_insert_local_inventory_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_list_local_inventories_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_list_local_inventories_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_delete_regional_inventory_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_delete_regional_inventory_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_insert_regional_inventory_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_insert_regional_inventory_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_list_regional_inventories_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_list_regional_inventories_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1.json (100%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/scripts/fixup_merchant_inventories_v1_keywords.py (100%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services => packages/google-shopping-merchant-inventories/tests/unit/gapic/merchant_inventories_v1}/__init__.py (100%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/tests/unit/gapic/merchant_inventories_v1/test_local_inventory_service.py (68%) rename {owl-bot-staging/google-shopping-merchant-inventories/v1 => packages/google-shopping-merchant-inventories}/tests/unit/gapic/merchant_inventories_v1/test_regional_inventory_service.py (68%) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/.coveragerc b/owl-bot-staging/google-shopping-merchant-inventories/v1/.coveragerc deleted file mode 100644 index b3835b541d48..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/shopping/merchant_inventories/__init__.py - google/shopping/merchant_inventories/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/.flake8 b/owl-bot-staging/google-shopping-merchant-inventories/v1/.flake8 deleted file mode 100644 index 90316de21489..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/.flake8 +++ /dev/null @@ -1,34 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -[flake8] -# TODO(https://github.com/googleapis/gapic-generator-python/issues/2333): -# Resolve flake8 lint issues -ignore = E203, E231, E266, E501, W503 -exclude = - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2333): - # Ensure that generated code passes flake8 lint - **/gapic/** - **/services/** - **/types/** - # Exclude Protobuf gencode - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/LICENSE b/owl-bot-staging/google-shopping-merchant-inventories/v1/LICENSE deleted file mode 100644 index d64569567334..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/MANIFEST.in b/owl-bot-staging/google-shopping-merchant-inventories/v1/MANIFEST.in deleted file mode 100644 index dae249ec8976..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/MANIFEST.in +++ /dev/null @@ -1,20 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -include README.rst LICENSE -recursive-include google *.py *.pyi *.json *.proto py.typed -recursive-include tests * -global-exclude *.py[co] -global-exclude __pycache__ diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/README.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1/README.rst deleted file mode 100644 index 373e5600ce98..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/README.rst +++ /dev/null @@ -1,143 +0,0 @@ -Python Client for Google Shopping Merchant Inventories API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Shopping Merchant Inventories API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library - - -Logging -------- - -This library uses the standard Python :code:`logging` functionality to log some RPC events that could be of interest for debugging and monitoring purposes. -Note the following: - -#. Logs may contain sensitive information. Take care to **restrict access to the logs** if they are saved, whether it be on local storage or on Google Cloud Logging. -#. Google may refine the occurrence, level, and content of various log messages in this library without flagging such changes as breaking. **Do not depend on immutability of the logging events**. -#. By default, the logging events from this library are not handled. You must **explicitly configure log handling** using one of the mechanisms below. - - -Simple, environment-based configuration -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -To enable logging for this library without any changes in your code, set the :code:`GOOGLE_SDK_PYTHON_LOGGING_SCOPE` environment variable to a valid Google -logging scope. This configures handling of logging events (at level :code:`logging.DEBUG` or higher) from this library in a default manner, emitting the logged -messages in a structured format. It does not currently allow customizing the logging levels captured nor the handlers, formatters, etc. used for any logging -event. - -A logging scope is a period-separated namespace that begins with :code:`google`, identifying the Python module or package to log. - -- Valid logging scopes: :code:`google`, :code:`google.cloud.asset.v1`, :code:`google.api`, :code:`google.auth`, etc. -- Invalid logging scopes: :code:`foo`, :code:`123`, etc. - -**NOTE**: If the logging scope is invalid, the library does not set up any logging handlers. - - -Examples -^^^^^^^^ - -- Enabling the default handler for all Google-based loggers - -.. code-block:: console - - export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google - -- Enabling the default handler for a specific Google module (for a client library called :code:`library_v1`): - -.. code-block:: console - - export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google.cloud.library_v1 - - -Advanced, code-based configuration -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can also configure a valid logging scope using Python's standard `logging` mechanism. - - -Examples -^^^^^^^^ - -- Configuring a handler for all Google-based loggers - -.. code-block:: python - - import logging - - from google.cloud.translate_v3 import translate - - base_logger = logging.getLogger("google") - base_logger.addHandler(logging.StreamHandler()) - base_logger.setLevel(logging.DEBUG) - -- Configuring a handler for a specific Google module (for a client library called :code:`library_v1`): - -.. code-block:: python - - import logging - - from google.cloud.translate_v3 import translate - - base_logger = logging.getLogger("google.cloud.library_v1") - base_logger.addHandler(logging.StreamHandler()) - base_logger.setLevel(logging.DEBUG) - - -Logging details -~~~~~~~~~~~~~~~ - -#. Regardless of which of the mechanisms above you use to configure logging for this library, by default logging events are not propagated up to the root - logger from the `google`-level logger. If you need the events to be propagated to the root logger, you must explicitly set - :code:`logging.getLogger("google").propagate = True` in your code. -#. You can mix the different logging configurations above for different Google modules. For example, you may want use a code-based logging configuration for - one library, but decide you need to also set up environment-based logging configuration for another library. - - #. If you attempt to use both code-based and environment-based configuration for the same module, the environment-based configuration will be ineffectual - if the code -based configuration gets applied first. - -#. The Google-specific logging configurations (default handlers for environment-based configuration; not propagating logging events to the root logger) get - executed the first time *any* client library is instantiated in your application, and only if the affected loggers have not been previously configured. - (This is the reason for 2.i. above.) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/_static/custom.css b/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/_static/custom.css deleted file mode 100644 index b0a295464b23..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/_static/custom.css +++ /dev/null @@ -1,20 +0,0 @@ -div#python2-eol { - border-color: red; - border-width: medium; -} - -/* Ensure minimum width for 'Parameters' / 'Returns' column */ -dl.field-list > dt { - min-width: 100px -} - -/* Insert space between methods for readability */ -dl.method { - padding-top: 10px; - padding-bottom: 10px -} - -/* Insert empty space between classes */ -dl.class { - padding-bottom: 50px -} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/_templates/layout.html b/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/_templates/layout.html deleted file mode 100644 index 95e9c77fcfe1..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/_templates/layout.html +++ /dev/null @@ -1,50 +0,0 @@ - -{% extends "!layout.html" %} -{%- block content %} -{%- if theme_fixed_sidebar|lower == 'true' %} -
- {{ sidebar() }} - {%- block document %} -
- {%- if render_sidebar %} -
- {%- endif %} - - {%- block relbar_top %} - {%- if theme_show_relbar_top|tobool %} - - {%- endif %} - {% endblock %} - -
-
- As of January 1, 2020 this library no longer supports Python 2 on the latest released version. - Library versions released prior to that date will continue to be available. For more information please - visit Python 2 support on Google Cloud. -
- {% block body %} {% endblock %} -
- - {%- block relbar_bottom %} - {%- if theme_show_relbar_bottom|tobool %} - - {%- endif %} - {% endblock %} - - {%- if render_sidebar %} -
- {%- endif %} -
- {%- endblock %} -
-
-{%- else %} -{{ super() }} -{%- endif %} -{%- endblock %} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/conf.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/conf.py deleted file mode 100644 index b4a1101f35ed..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/conf.py +++ /dev/null @@ -1,385 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-shopping-merchant-inventories documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# 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 -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -# For plugins that can not read conf.py. -# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 -sys.path.insert(0, os.path.abspath(".")) - -__version__ = "" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.5.0" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.doctest", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", - "recommonmark", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_options = {"members": True} -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -# source_suffix = ['.rst', '.md'] -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-shopping-merchant-inventories" -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 -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = [ - "_build", - "**/.nox/**/*", - "samples/AUTHORING_GUIDE.md", - "samples/CONTRIBUTING.md", - "samples/snippets/README.rst", -] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Shopping Client Libraries for google-shopping-merchant-inventories", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-shopping-merchant-inventories-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-shopping-merchant-inventories.tex", - u"google-shopping-merchant-inventories Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-shopping-merchant-inventories", - "google-shopping-merchant-inventories Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-shopping-merchant-inventories", - "google-shopping-merchant-inventories Documentation", - author, - "google-shopping-merchant-inventories", - "google-shopping-merchant-inventories Library", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("https://python.readthedocs.org/en/latest/", None), - "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None), - "google.api_core": ( - "https://googleapis.dev/python/google-api-core/latest/", - None, - ), - "grpc": ("https://grpc.github.io/grpc/python/", None), - "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/index.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/index.rst deleted file mode 100644 index f63408727d88..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/index.rst +++ /dev/null @@ -1,10 +0,0 @@ -.. include:: multiprocessing.rst - - -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - merchant_inventories_v1/services_ - merchant_inventories_v1/types_ diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/multiprocessing.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/multiprocessing.rst deleted file mode 100644 index 536d17b2ea65..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/multiprocessing.rst +++ /dev/null @@ -1,7 +0,0 @@ -.. note:: - - Because this client uses :mod:`grpc` library, it is safe to - share instances across threads. In multiprocessing scenarios, the best - practice is to create client instances *after* the invocation of - :func:`os.fork` by :class:`multiprocessing.pool.Pool` or - :class:`multiprocessing.Process`. diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories/__init__.py deleted file mode 100644 index a859205efe72..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories/__init__.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.shopping.merchant_inventories import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.shopping.merchant_inventories_v1.services.local_inventory_service.client import LocalInventoryServiceClient -from google.shopping.merchant_inventories_v1.services.local_inventory_service.async_client import LocalInventoryServiceAsyncClient -from google.shopping.merchant_inventories_v1.services.regional_inventory_service.client import RegionalInventoryServiceClient -from google.shopping.merchant_inventories_v1.services.regional_inventory_service.async_client import RegionalInventoryServiceAsyncClient - -from google.shopping.merchant_inventories_v1.types.inventories_common import LocalInventoryAttributes -from google.shopping.merchant_inventories_v1.types.inventories_common import RegionalInventoryAttributes -from google.shopping.merchant_inventories_v1.types.localinventory import DeleteLocalInventoryRequest -from google.shopping.merchant_inventories_v1.types.localinventory import InsertLocalInventoryRequest -from google.shopping.merchant_inventories_v1.types.localinventory import ListLocalInventoriesRequest -from google.shopping.merchant_inventories_v1.types.localinventory import ListLocalInventoriesResponse -from google.shopping.merchant_inventories_v1.types.localinventory import LocalInventory -from google.shopping.merchant_inventories_v1.types.regionalinventory import DeleteRegionalInventoryRequest -from google.shopping.merchant_inventories_v1.types.regionalinventory import InsertRegionalInventoryRequest -from google.shopping.merchant_inventories_v1.types.regionalinventory import ListRegionalInventoriesRequest -from google.shopping.merchant_inventories_v1.types.regionalinventory import ListRegionalInventoriesResponse -from google.shopping.merchant_inventories_v1.types.regionalinventory import RegionalInventory - -__all__ = ('LocalInventoryServiceClient', - 'LocalInventoryServiceAsyncClient', - 'RegionalInventoryServiceClient', - 'RegionalInventoryServiceAsyncClient', - 'LocalInventoryAttributes', - 'RegionalInventoryAttributes', - 'DeleteLocalInventoryRequest', - 'InsertLocalInventoryRequest', - 'ListLocalInventoriesRequest', - 'ListLocalInventoriesResponse', - 'LocalInventory', - 'DeleteRegionalInventoryRequest', - 'InsertRegionalInventoryRequest', - 'ListRegionalInventoriesRequest', - 'ListRegionalInventoriesResponse', - 'RegionalInventory', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/__init__.py deleted file mode 100644 index 501eb2a58870..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/__init__.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.shopping.merchant_inventories_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.local_inventory_service import LocalInventoryServiceClient -from .services.local_inventory_service import LocalInventoryServiceAsyncClient -from .services.regional_inventory_service import RegionalInventoryServiceClient -from .services.regional_inventory_service import RegionalInventoryServiceAsyncClient - -from .types.inventories_common import LocalInventoryAttributes -from .types.inventories_common import RegionalInventoryAttributes -from .types.localinventory import DeleteLocalInventoryRequest -from .types.localinventory import InsertLocalInventoryRequest -from .types.localinventory import ListLocalInventoriesRequest -from .types.localinventory import ListLocalInventoriesResponse -from .types.localinventory import LocalInventory -from .types.regionalinventory import DeleteRegionalInventoryRequest -from .types.regionalinventory import InsertRegionalInventoryRequest -from .types.regionalinventory import ListRegionalInventoriesRequest -from .types.regionalinventory import ListRegionalInventoriesResponse -from .types.regionalinventory import RegionalInventory - -__all__ = ( - 'LocalInventoryServiceAsyncClient', - 'RegionalInventoryServiceAsyncClient', -'DeleteLocalInventoryRequest', -'DeleteRegionalInventoryRequest', -'InsertLocalInventoryRequest', -'InsertRegionalInventoryRequest', -'ListLocalInventoriesRequest', -'ListLocalInventoriesResponse', -'ListRegionalInventoriesRequest', -'ListRegionalInventoriesResponse', -'LocalInventory', -'LocalInventoryAttributes', -'LocalInventoryServiceClient', -'RegionalInventory', -'RegionalInventoryAttributes', -'RegionalInventoryServiceClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/gapic_version.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/gapic_version.py deleted file mode 100644 index 20a9cd975b02..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/py.typed b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/py.typed deleted file mode 100644 index 993f00a7e3c3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-shopping-merchant-inventories package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/__init__.py deleted file mode 100644 index b26a37767f11..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import RegionalInventoryServiceTransport -from .grpc import RegionalInventoryServiceGrpcTransport -from .grpc_asyncio import RegionalInventoryServiceGrpcAsyncIOTransport -from .rest import RegionalInventoryServiceRestTransport -from .rest import RegionalInventoryServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[RegionalInventoryServiceTransport]] -_transport_registry['grpc'] = RegionalInventoryServiceGrpcTransport -_transport_registry['grpc_asyncio'] = RegionalInventoryServiceGrpcAsyncIOTransport -_transport_registry['rest'] = RegionalInventoryServiceRestTransport - -__all__ = ( - 'RegionalInventoryServiceTransport', - 'RegionalInventoryServiceGrpcTransport', - 'RegionalInventoryServiceGrpcAsyncIOTransport', - 'RegionalInventoryServiceRestTransport', - 'RegionalInventoryServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/__init__.py deleted file mode 100644 index b6ff0b1dac5e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/__init__.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .inventories_common import ( - LocalInventoryAttributes, - RegionalInventoryAttributes, -) -from .localinventory import ( - DeleteLocalInventoryRequest, - InsertLocalInventoryRequest, - ListLocalInventoriesRequest, - ListLocalInventoriesResponse, - LocalInventory, -) -from .regionalinventory import ( - DeleteRegionalInventoryRequest, - InsertRegionalInventoryRequest, - ListRegionalInventoriesRequest, - ListRegionalInventoriesResponse, - RegionalInventory, -) - -__all__ = ( - 'LocalInventoryAttributes', - 'RegionalInventoryAttributes', - 'DeleteLocalInventoryRequest', - 'InsertLocalInventoryRequest', - 'ListLocalInventoriesRequest', - 'ListLocalInventoriesResponse', - 'LocalInventory', - 'DeleteRegionalInventoryRequest', - 'InsertRegionalInventoryRequest', - 'ListRegionalInventoriesRequest', - 'ListRegionalInventoriesResponse', - 'RegionalInventory', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/mypy.ini b/owl-bot-staging/google-shopping-merchant-inventories/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/noxfile.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/noxfile.py deleted file mode 100644 index 084984b159e7..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/noxfile.py +++ /dev/null @@ -1,591 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import re -import shutil - -from typing import Dict, List -import warnings - -import nox - -BLACK_VERSION = "black[jupyter]==23.7.0" -ISORT_VERSION = "isort==5.11.0" - -LINT_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -DEFAULT_PYTHON_VERSION = ALL_PYTHON[-1] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = "google-shopping-merchant-inventories" - -UNIT_TEST_STANDARD_DEPENDENCIES = [ - "mock", - "asyncmock", - "pytest", - "pytest-cov", - "pytest-asyncio", -] -UNIT_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] -UNIT_TEST_LOCAL_DEPENDENCIES: List[str] = [] -UNIT_TEST_DEPENDENCIES: List[str] = [] -UNIT_TEST_EXTRAS: List[str] = [] -UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} - -SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] -SYSTEM_TEST_STANDARD_DEPENDENCIES = [ - "mock", - "pytest", - "google-cloud-testutils", -] -SYSTEM_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] -SYSTEM_TEST_LOCAL_DEPENDENCIES: List[str] = [] -SYSTEM_TEST_DEPENDENCIES: List[str] = [] -SYSTEM_TEST_EXTRAS: List[str] = [] -SYSTEM_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} - -nox.options.sessions = [ - "unit", - "system", - "cover", - "lint", - "lint_setup_py", - "blacken", - "docs", -] - -# Error if a python version is missing -nox.options.error_on_missing_interpreters = True - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - "mypy", - "types-requests", - "types-protobuf", - ) - session.install(".") - session.run( - "mypy", - "-p", - "google", - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install("google-cloud-testutils") - session.install(".") - - session.run( - "lower-bound-checker", - "update", - "--package-name", - PACKAGE_NAME, - "--constraints-file", - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install("google-cloud-testutils") - session.install(".") - - session.run( - "lower-bound-checker", - "check", - "--package-name", - PACKAGE_NAME, - "--constraints-file", - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *LINT_PATHS, - ) - - session.run("flake8", "google", "tests") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *LINT_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def format(session): - """ - Run isort to sort imports. Then run black - to format code to uniform standard. - """ - session.install(BLACK_VERSION, ISORT_VERSION) - # Use the --fss option to sort imports using strict alphabetical order. - # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections - session.run( - "isort", - "--fss", - *LINT_PATHS, - ) - session.run( - "black", - *LINT_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("setuptools", "docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") - - -def install_unittest_dependencies(session, *constraints): - standard_deps = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_DEPENDENCIES - session.install(*standard_deps, *constraints) - - if UNIT_TEST_EXTERNAL_DEPENDENCIES: - warnings.warn( - "'unit_test_external_dependencies' is deprecated. Instead, please " - "use 'unit_test_dependencies' or 'unit_test_local_dependencies'.", - DeprecationWarning, - ) - session.install(*UNIT_TEST_EXTERNAL_DEPENDENCIES, *constraints) - - if UNIT_TEST_LOCAL_DEPENDENCIES: - session.install(*UNIT_TEST_LOCAL_DEPENDENCIES, *constraints) - - if UNIT_TEST_EXTRAS_BY_PYTHON: - extras = UNIT_TEST_EXTRAS_BY_PYTHON.get(session.python, []) - elif UNIT_TEST_EXTRAS: - extras = UNIT_TEST_EXTRAS - else: - extras = [] - - if extras: - session.install("-e", f".[{','.join(extras)}]", *constraints) - else: - session.install("-e", ".", *constraints) - - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - ["python", "upb", "cpp"], -) -def unit(session, protobuf_implementation): - # Install all test dependencies, then install this package in-place. - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): - session.skip("cpp implementation is not supported in python 3.11+") - - constraints_path = str( - CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" - ) - install_unittest_dependencies(session, "-c", constraints_path) - - # TODO(https://github.com/googleapis/synthtool/issues/1976): - # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. - # The 'cpp' implementation requires Protobuf<4. - if protobuf_implementation == "cpp": - session.install("protobuf<4") - - # Run py.test against the unit tests. - session.run( - "py.test", - "--quiet", - f"--junitxml=unit_{session.python}_sponge_log.xml", - "--cov=google", - "--cov=tests/unit", - "--cov-append", - "--cov-config=.coveragerc", - "--cov-report=", - "--cov-fail-under=0", - os.path.join("tests", "unit"), - *session.posargs, - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -def install_systemtest_dependencies(session, *constraints): - session.install("--pre", "grpcio") - - session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_EXTERNAL_DEPENDENCIES: - session.install(*SYSTEM_TEST_EXTERNAL_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_LOCAL_DEPENDENCIES: - session.install("-e", *SYSTEM_TEST_LOCAL_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_DEPENDENCIES: - session.install("-e", *SYSTEM_TEST_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_EXTRAS_BY_PYTHON: - extras = SYSTEM_TEST_EXTRAS_BY_PYTHON.get(session.python, []) - elif SYSTEM_TEST_EXTRAS: - extras = SYSTEM_TEST_EXTRAS - else: - extras = [] - - if extras: - session.install("-e", f".[{','.join(extras)}]", *constraints) - else: - session.install("-e", ".", *constraints) - - -@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) -def system(session): - """Run the system test suite.""" - constraints_path = str( - CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" - ) - system_test_path = os.path.join("tests", "system.py") - system_test_folder_path = os.path.join("tests", "system") - - # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. - if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": - session.skip("RUN_SYSTEM_TESTS is set to false, skipping") - # Install pyopenssl for mTLS testing. - if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": - session.install("pyopenssl") - - system_test_exists = os.path.exists(system_test_path) - system_test_folder_exists = os.path.exists(system_test_folder_path) - # Sanity check: only run tests if found. - if not system_test_exists and not system_test_folder_exists: - session.skip("System tests were not found") - - install_systemtest_dependencies(session, "-c", constraints_path) - - # Run py.test against the system tests. - if system_test_exists: - session.run( - "py.test", - "--quiet", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_path, - *session.posargs, - ) - if system_test_folder_exists: - session.run( - "py.test", - "--quiet", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_folder_path, - *session.posargs, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python="3.10") -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install( - # We need to pin to specific versions of the `sphinxcontrib-*` packages - # which still support sphinx 4.x. - # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 - # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. - "sphinxcontrib-applehelp==1.0.4", - "sphinxcontrib-devhelp==1.0.2", - "sphinxcontrib-htmlhelp==2.0.1", - "sphinxcontrib-qthelp==1.0.3", - "sphinxcontrib-serializinghtml==1.1.5", - "sphinx==4.5.0", - "alabaster", - "recommonmark", - ) - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python="3.10") -def docfx(session): - """Build the docfx yaml files for this library.""" - - session.install("-e", ".") - session.install( - # We need to pin to specific versions of the `sphinxcontrib-*` packages - # which still support sphinx 4.x. - # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 - # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. - "sphinxcontrib-applehelp==1.0.4", - "sphinxcontrib-devhelp==1.0.2", - "sphinxcontrib-htmlhelp==2.0.1", - "sphinxcontrib-qthelp==1.0.3", - "sphinxcontrib-serializinghtml==1.1.5", - "gcp-sphinx-docfx-yaml", - "alabaster", - "recommonmark", - ) - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-T", # show full traceback on exception - "-N", # no colors - "-D", - ( - "extensions=sphinx.ext.autodoc," - "sphinx.ext.autosummary," - "docfx_yaml.extension," - "sphinx.ext.intersphinx," - "sphinx.ext.coverage," - "sphinx.ext.napoleon," - "sphinx.ext.todo," - "sphinx.ext.viewcode," - "recommonmark" - ), - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -@nox.parametrize( - "protobuf_implementation", - ["python", "upb", "cpp"], -) -def prerelease_deps(session, protobuf_implementation): - """ - Run all tests with pre-release versions of dependencies installed - rather than the standard non pre-release versions. - Pre-release versions can be installed using - `pip install --pre `. - """ - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): - session.skip("cpp implementation is not supported in python 3.11+") - - # Install all dependencies - session.install("-e", ".") - - # Install dependencies for the unit test environment - unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES - session.install(*unit_deps_all) - - # Install dependencies for the system test environment - system_deps_all = ( - SYSTEM_TEST_STANDARD_DEPENDENCIES - + SYSTEM_TEST_EXTERNAL_DEPENDENCIES - + SYSTEM_TEST_EXTRAS - ) - session.install(*system_deps_all) - - # Because we test minimum dependency versions on the minimum Python - # version, the first version we test with in the unit tests sessions has a - # constraints file containing all dependencies and extras. - with open( - CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) - - # Note: If a dependency is added to the `prerel_deps` list, - # the `core_dependencies_from_source` list in the `core_deps_from_source` - # nox session should also be updated. - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - "grpc-google-iam-v1", - "grpcio", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--ignore-installed", dep) - # TODO(https://github.com/grpc/grpc/issues/38965): Add `grpcio-status`` - # to the dictionary below once this bug is fixed. - # TODO(https://github.com/googleapis/google-cloud-python/issues/13643): Add - # `googleapis-common-protos` and `grpc-google-iam-v1` to the dictionary below - # once this bug is fixed. - package_namespaces = { - "google-api-core": "google.api_core", - "google-auth": "google.auth", - "grpcio": "grpc", - "protobuf": "google.protobuf", - "proto-plus": "proto", - } - - version_namespace = package_namespaces.get(dep) - - print(f"Installed {dep}") - if version_namespace: - session.run( - "python", - "-c", - f"import {version_namespace}; print({version_namespace}.__version__)", - ) - - session.run( - "py.test", - "tests/unit", - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -@nox.parametrize( - "protobuf_implementation", - ["python", "upb"], -) -def core_deps_from_source(session, protobuf_implementation): - """Run all tests with core dependencies installed from source - rather than pulling the dependencies from PyPI. - """ - - # Install all dependencies - session.install("-e", ".") - - # Install dependencies for the unit test environment - unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES - session.install(*unit_deps_all) - - # Install dependencies for the system test environment - system_deps_all = ( - SYSTEM_TEST_STANDARD_DEPENDENCIES - + SYSTEM_TEST_EXTERNAL_DEPENDENCIES - + SYSTEM_TEST_EXTRAS - ) - session.install(*system_deps_all) - - # Because we test minimum dependency versions on the minimum Python - # version, the first version we test with in the unit tests sessions has a - # constraints file containing all dependencies and extras. - with open( - CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) - - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and - # `grpcio-status` should be added to the list below so that they are installed from source, - # rather than PyPI. - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2357): `protobuf` should be - # added to the list below so that it is installed from source, rather than PyPI - # Note: If a dependency is added to the `core_dependencies_from_source` list, - # the `prerel_deps` list in the `prerelease_deps` nox session should also be updated. - core_dependencies_from_source = [ - "googleapis-common-protos @ git+https://github.com/googleapis/google-cloud-python#egg=googleapis-common-protos&subdirectory=packages/googleapis-common-protos", - "google-api-core @ git+https://github.com/googleapis/python-api-core.git", - "google-auth @ git+https://github.com/googleapis/google-auth-library-python.git", - "grpc-google-iam-v1 @ git+https://github.com/googleapis/google-cloud-python#egg=grpc-google-iam-v1&subdirectory=packages/grpc-google-iam-v1", - "proto-plus @ git+https://github.com/googleapis/proto-plus-python.git", - ] - - for dep in core_dependencies_from_source: - session.install(dep, "--no-deps", "--ignore-installed") - print(f"Installed {dep}") - - session.run( - "py.test", - "tests/unit", - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/setup.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/setup.py deleted file mode 100644 index 4fd17ebb95a5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/setup.py +++ /dev/null @@ -1,99 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import re - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-shopping-merchant-inventories' - - -description = "Google Shopping Merchant Inventories API client library" - -version = None - -with open(os.path.join(package_root, 'google/shopping/merchant_inventories/gapic_version.py')) as fp: - version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) - assert (len(version_candidates) == 1) - version = version_candidates[0] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.1, <3.0.0,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - # Exclude incompatible versions of `google-auth` - # See https://github.com/googleapis/google-cloud-python/issues/12364 - "google-auth >= 2.14.1, <3.0.0,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0", - "proto-plus >= 1.25.0, <2.0.0; python_version >= '3.13'", - "protobuf>=3.20.2,<7.0.0,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", - "google-shopping-type >= 0.1.6, <1.0.0", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-inventories" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.find_namespace_packages() - if package.startswith("google") -] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - extras_require=extras, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.10.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.10.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.11.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.11.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.12.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.12.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.13.txt deleted file mode 100644 index 0112695e5bbb..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.13.txt +++ /dev/null @@ -1,12 +0,0 @@ -# We use the constraints file for the latest Python version -# (currently this file) to check that the latest -# major versions of dependencies are supported in setup.py. -# List all library dependencies and extras in this file. -# Require the latest major version be installed for each dependency. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# Then this file should have google-cloud-foo>=1 -google-api-core>=2 -google-auth>=2 -proto-plus>=1 -protobuf>=6 -google-shopping-type>=0 diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.7.txt deleted file mode 100644 index 2af887ec8ba0..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.7.txt +++ /dev/null @@ -1,11 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.1 -google-auth==2.14.1 -proto-plus==1.22.3 -protobuf==3.20.2 -google-shopping-type==0.1.6 diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.8.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.8.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.9.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/testing/constraints-3.9.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/merchant_inventories_v1/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/merchant_inventories_v1/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/merchant_inventories_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/.coveragerc b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/.coveragerc deleted file mode 100644 index b3835b541d48..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/shopping/merchant_inventories/__init__.py - google/shopping/merchant_inventories/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/.flake8 b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/.flake8 deleted file mode 100644 index 90316de21489..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/.flake8 +++ /dev/null @@ -1,34 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -[flake8] -# TODO(https://github.com/googleapis/gapic-generator-python/issues/2333): -# Resolve flake8 lint issues -ignore = E203, E231, E266, E501, W503 -exclude = - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2333): - # Ensure that generated code passes flake8 lint - **/gapic/** - **/services/** - **/types/** - # Exclude Protobuf gencode - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/LICENSE b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/LICENSE deleted file mode 100644 index d64569567334..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/MANIFEST.in b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/MANIFEST.in deleted file mode 100644 index dae249ec8976..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/MANIFEST.in +++ /dev/null @@ -1,20 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -include README.rst LICENSE -recursive-include google *.py *.pyi *.json *.proto py.typed -recursive-include tests * -global-exclude *.py[co] -global-exclude __pycache__ diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/README.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/README.rst deleted file mode 100644 index 373e5600ce98..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/README.rst +++ /dev/null @@ -1,143 +0,0 @@ -Python Client for Google Shopping Merchant Inventories API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Shopping Merchant Inventories API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library - - -Logging -------- - -This library uses the standard Python :code:`logging` functionality to log some RPC events that could be of interest for debugging and monitoring purposes. -Note the following: - -#. Logs may contain sensitive information. Take care to **restrict access to the logs** if they are saved, whether it be on local storage or on Google Cloud Logging. -#. Google may refine the occurrence, level, and content of various log messages in this library without flagging such changes as breaking. **Do not depend on immutability of the logging events**. -#. By default, the logging events from this library are not handled. You must **explicitly configure log handling** using one of the mechanisms below. - - -Simple, environment-based configuration -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -To enable logging for this library without any changes in your code, set the :code:`GOOGLE_SDK_PYTHON_LOGGING_SCOPE` environment variable to a valid Google -logging scope. This configures handling of logging events (at level :code:`logging.DEBUG` or higher) from this library in a default manner, emitting the logged -messages in a structured format. It does not currently allow customizing the logging levels captured nor the handlers, formatters, etc. used for any logging -event. - -A logging scope is a period-separated namespace that begins with :code:`google`, identifying the Python module or package to log. - -- Valid logging scopes: :code:`google`, :code:`google.cloud.asset.v1`, :code:`google.api`, :code:`google.auth`, etc. -- Invalid logging scopes: :code:`foo`, :code:`123`, etc. - -**NOTE**: If the logging scope is invalid, the library does not set up any logging handlers. - - -Examples -^^^^^^^^ - -- Enabling the default handler for all Google-based loggers - -.. code-block:: console - - export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google - -- Enabling the default handler for a specific Google module (for a client library called :code:`library_v1`): - -.. code-block:: console - - export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google.cloud.library_v1 - - -Advanced, code-based configuration -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can also configure a valid logging scope using Python's standard `logging` mechanism. - - -Examples -^^^^^^^^ - -- Configuring a handler for all Google-based loggers - -.. code-block:: python - - import logging - - from google.cloud.translate_v3 import translate - - base_logger = logging.getLogger("google") - base_logger.addHandler(logging.StreamHandler()) - base_logger.setLevel(logging.DEBUG) - -- Configuring a handler for a specific Google module (for a client library called :code:`library_v1`): - -.. code-block:: python - - import logging - - from google.cloud.translate_v3 import translate - - base_logger = logging.getLogger("google.cloud.library_v1") - base_logger.addHandler(logging.StreamHandler()) - base_logger.setLevel(logging.DEBUG) - - -Logging details -~~~~~~~~~~~~~~~ - -#. Regardless of which of the mechanisms above you use to configure logging for this library, by default logging events are not propagated up to the root - logger from the `google`-level logger. If you need the events to be propagated to the root logger, you must explicitly set - :code:`logging.getLogger("google").propagate = True` in your code. -#. You can mix the different logging configurations above for different Google modules. For example, you may want use a code-based logging configuration for - one library, but decide you need to also set up environment-based logging configuration for another library. - - #. If you attempt to use both code-based and environment-based configuration for the same module, the environment-based configuration will be ineffectual - if the code -based configuration gets applied first. - -#. The Google-specific logging configurations (default handlers for environment-based configuration; not propagating logging events to the root logger) get - executed the first time *any* client library is instantiated in your application, and only if the affected loggers have not been previously configured. - (This is the reason for 2.i. above.) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/_static/custom.css b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/_static/custom.css deleted file mode 100644 index b0a295464b23..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/_static/custom.css +++ /dev/null @@ -1,20 +0,0 @@ -div#python2-eol { - border-color: red; - border-width: medium; -} - -/* Ensure minimum width for 'Parameters' / 'Returns' column */ -dl.field-list > dt { - min-width: 100px -} - -/* Insert space between methods for readability */ -dl.method { - padding-top: 10px; - padding-bottom: 10px -} - -/* Insert empty space between classes */ -dl.class { - padding-bottom: 50px -} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/_templates/layout.html b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/_templates/layout.html deleted file mode 100644 index 95e9c77fcfe1..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/_templates/layout.html +++ /dev/null @@ -1,50 +0,0 @@ - -{% extends "!layout.html" %} -{%- block content %} -{%- if theme_fixed_sidebar|lower == 'true' %} -
- {{ sidebar() }} - {%- block document %} -
- {%- if render_sidebar %} -
- {%- endif %} - - {%- block relbar_top %} - {%- if theme_show_relbar_top|tobool %} - - {%- endif %} - {% endblock %} - -
-
- As of January 1, 2020 this library no longer supports Python 2 on the latest released version. - Library versions released prior to that date will continue to be available. For more information please - visit Python 2 support on Google Cloud. -
- {% block body %} {% endblock %} -
- - {%- block relbar_bottom %} - {%- if theme_show_relbar_bottom|tobool %} - - {%- endif %} - {% endblock %} - - {%- if render_sidebar %} -
- {%- endif %} -
- {%- endblock %} -
-
-{%- else %} -{{ super() }} -{%- endif %} -{%- endblock %} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/conf.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/conf.py deleted file mode 100644 index b4a1101f35ed..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/conf.py +++ /dev/null @@ -1,385 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-shopping-merchant-inventories documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# 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 -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -# For plugins that can not read conf.py. -# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 -sys.path.insert(0, os.path.abspath(".")) - -__version__ = "" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.5.0" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.doctest", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", - "recommonmark", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_options = {"members": True} -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -# source_suffix = ['.rst', '.md'] -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-shopping-merchant-inventories" -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 -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = [ - "_build", - "**/.nox/**/*", - "samples/AUTHORING_GUIDE.md", - "samples/CONTRIBUTING.md", - "samples/snippets/README.rst", -] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Shopping Client Libraries for google-shopping-merchant-inventories", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-shopping-merchant-inventories-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-shopping-merchant-inventories.tex", - u"google-shopping-merchant-inventories Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-shopping-merchant-inventories", - "google-shopping-merchant-inventories Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-shopping-merchant-inventories", - "google-shopping-merchant-inventories Documentation", - author, - "google-shopping-merchant-inventories", - "google-shopping-merchant-inventories Library", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("https://python.readthedocs.org/en/latest/", None), - "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None), - "google.api_core": ( - "https://googleapis.dev/python/google-api-core/latest/", - None, - ), - "grpc": ("https://grpc.github.io/grpc/python/", None), - "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/index.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/index.rst deleted file mode 100644 index d9a85dd953d7..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/index.rst +++ /dev/null @@ -1,10 +0,0 @@ -.. include:: multiprocessing.rst - - -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - merchant_inventories_v1beta/services_ - merchant_inventories_v1beta/types_ diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/local_inventory_service.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/local_inventory_service.rst deleted file mode 100644 index d8e5a2b05114..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/local_inventory_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -LocalInventoryService ---------------------------------------- - -.. automodule:: google.shopping.merchant_inventories_v1beta.services.local_inventory_service - :members: - :inherited-members: - -.. automodule:: google.shopping.merchant_inventories_v1beta.services.local_inventory_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/regional_inventory_service.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/regional_inventory_service.rst deleted file mode 100644 index d23b466a2398..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/regional_inventory_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -RegionalInventoryService ------------------------------------------- - -.. automodule:: google.shopping.merchant_inventories_v1beta.services.regional_inventory_service - :members: - :inherited-members: - -.. automodule:: google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/services_.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/services_.rst deleted file mode 100644 index 7bdd71de9b95..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/services_.rst +++ /dev/null @@ -1,7 +0,0 @@ -Services for Google Shopping Merchant Inventories v1beta API -============================================================ -.. toctree:: - :maxdepth: 2 - - local_inventory_service - regional_inventory_service diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/types_.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/types_.rst deleted file mode 100644 index 2bd5b6e3cb01..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/merchant_inventories_v1beta/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Shopping Merchant Inventories v1beta API -========================================================= - -.. automodule:: google.shopping.merchant_inventories_v1beta.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/multiprocessing.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/multiprocessing.rst deleted file mode 100644 index 536d17b2ea65..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/docs/multiprocessing.rst +++ /dev/null @@ -1,7 +0,0 @@ -.. note:: - - Because this client uses :mod:`grpc` library, it is safe to - share instances across threads. In multiprocessing scenarios, the best - practice is to create client instances *after* the invocation of - :func:`os.fork` by :class:`multiprocessing.pool.Pool` or - :class:`multiprocessing.Process`. diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/__init__.py deleted file mode 100644 index 381ccc39f545..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/__init__.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.shopping.merchant_inventories import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.shopping.merchant_inventories_v1beta.services.local_inventory_service.client import LocalInventoryServiceClient -from google.shopping.merchant_inventories_v1beta.services.local_inventory_service.async_client import LocalInventoryServiceAsyncClient -from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.client import RegionalInventoryServiceClient -from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.async_client import RegionalInventoryServiceAsyncClient - -from google.shopping.merchant_inventories_v1beta.types.localinventory import DeleteLocalInventoryRequest -from google.shopping.merchant_inventories_v1beta.types.localinventory import InsertLocalInventoryRequest -from google.shopping.merchant_inventories_v1beta.types.localinventory import ListLocalInventoriesRequest -from google.shopping.merchant_inventories_v1beta.types.localinventory import ListLocalInventoriesResponse -from google.shopping.merchant_inventories_v1beta.types.localinventory import LocalInventory -from google.shopping.merchant_inventories_v1beta.types.regionalinventory import DeleteRegionalInventoryRequest -from google.shopping.merchant_inventories_v1beta.types.regionalinventory import InsertRegionalInventoryRequest -from google.shopping.merchant_inventories_v1beta.types.regionalinventory import ListRegionalInventoriesRequest -from google.shopping.merchant_inventories_v1beta.types.regionalinventory import ListRegionalInventoriesResponse -from google.shopping.merchant_inventories_v1beta.types.regionalinventory import RegionalInventory - -__all__ = ('LocalInventoryServiceClient', - 'LocalInventoryServiceAsyncClient', - 'RegionalInventoryServiceClient', - 'RegionalInventoryServiceAsyncClient', - 'DeleteLocalInventoryRequest', - 'InsertLocalInventoryRequest', - 'ListLocalInventoriesRequest', - 'ListLocalInventoriesResponse', - 'LocalInventory', - 'DeleteRegionalInventoryRequest', - 'InsertRegionalInventoryRequest', - 'ListRegionalInventoriesRequest', - 'ListRegionalInventoriesResponse', - 'RegionalInventory', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/gapic_version.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/gapic_version.py deleted file mode 100644 index 20a9cd975b02..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/py.typed b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/py.typed deleted file mode 100644 index 993f00a7e3c3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-shopping-merchant-inventories package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/__init__.py deleted file mode 100644 index a26ccce0e474..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/__init__.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.shopping.merchant_inventories_v1beta import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.local_inventory_service import LocalInventoryServiceClient -from .services.local_inventory_service import LocalInventoryServiceAsyncClient -from .services.regional_inventory_service import RegionalInventoryServiceClient -from .services.regional_inventory_service import RegionalInventoryServiceAsyncClient - -from .types.localinventory import DeleteLocalInventoryRequest -from .types.localinventory import InsertLocalInventoryRequest -from .types.localinventory import ListLocalInventoriesRequest -from .types.localinventory import ListLocalInventoriesResponse -from .types.localinventory import LocalInventory -from .types.regionalinventory import DeleteRegionalInventoryRequest -from .types.regionalinventory import InsertRegionalInventoryRequest -from .types.regionalinventory import ListRegionalInventoriesRequest -from .types.regionalinventory import ListRegionalInventoriesResponse -from .types.regionalinventory import RegionalInventory - -__all__ = ( - 'LocalInventoryServiceAsyncClient', - 'RegionalInventoryServiceAsyncClient', -'DeleteLocalInventoryRequest', -'DeleteRegionalInventoryRequest', -'InsertLocalInventoryRequest', -'InsertRegionalInventoryRequest', -'ListLocalInventoriesRequest', -'ListLocalInventoriesResponse', -'ListRegionalInventoriesRequest', -'ListRegionalInventoriesResponse', -'LocalInventory', -'LocalInventoryServiceClient', -'RegionalInventory', -'RegionalInventoryServiceClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_metadata.json b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_metadata.json deleted file mode 100644 index dca053900305..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_metadata.json +++ /dev/null @@ -1,137 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.shopping.merchant_inventories_v1beta", - "protoPackage": "google.shopping.merchant.inventories.v1beta", - "schema": "1.0", - "services": { - "LocalInventoryService": { - "clients": { - "grpc": { - "libraryClient": "LocalInventoryServiceClient", - "rpcs": { - "DeleteLocalInventory": { - "methods": [ - "delete_local_inventory" - ] - }, - "InsertLocalInventory": { - "methods": [ - "insert_local_inventory" - ] - }, - "ListLocalInventories": { - "methods": [ - "list_local_inventories" - ] - } - } - }, - "grpc-async": { - "libraryClient": "LocalInventoryServiceAsyncClient", - "rpcs": { - "DeleteLocalInventory": { - "methods": [ - "delete_local_inventory" - ] - }, - "InsertLocalInventory": { - "methods": [ - "insert_local_inventory" - ] - }, - "ListLocalInventories": { - "methods": [ - "list_local_inventories" - ] - } - } - }, - "rest": { - "libraryClient": "LocalInventoryServiceClient", - "rpcs": { - "DeleteLocalInventory": { - "methods": [ - "delete_local_inventory" - ] - }, - "InsertLocalInventory": { - "methods": [ - "insert_local_inventory" - ] - }, - "ListLocalInventories": { - "methods": [ - "list_local_inventories" - ] - } - } - } - } - }, - "RegionalInventoryService": { - "clients": { - "grpc": { - "libraryClient": "RegionalInventoryServiceClient", - "rpcs": { - "DeleteRegionalInventory": { - "methods": [ - "delete_regional_inventory" - ] - }, - "InsertRegionalInventory": { - "methods": [ - "insert_regional_inventory" - ] - }, - "ListRegionalInventories": { - "methods": [ - "list_regional_inventories" - ] - } - } - }, - "grpc-async": { - "libraryClient": "RegionalInventoryServiceAsyncClient", - "rpcs": { - "DeleteRegionalInventory": { - "methods": [ - "delete_regional_inventory" - ] - }, - "InsertRegionalInventory": { - "methods": [ - "insert_regional_inventory" - ] - }, - "ListRegionalInventories": { - "methods": [ - "list_regional_inventories" - ] - } - } - }, - "rest": { - "libraryClient": "RegionalInventoryServiceClient", - "rpcs": { - "DeleteRegionalInventory": { - "methods": [ - "delete_regional_inventory" - ] - }, - "InsertRegionalInventory": { - "methods": [ - "insert_regional_inventory" - ] - }, - "ListRegionalInventories": { - "methods": [ - "list_regional_inventories" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_version.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_version.py deleted file mode 100644 index 20a9cd975b02..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/py.typed b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/py.typed deleted file mode 100644 index 993f00a7e3c3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-shopping-merchant-inventories package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/__init__.py deleted file mode 100644 index 4b805a80aace..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import LocalInventoryServiceClient -from .async_client import LocalInventoryServiceAsyncClient - -__all__ = ( - 'LocalInventoryServiceClient', - 'LocalInventoryServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/async_client.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/async_client.py deleted file mode 100644 index 582b1f5798c7..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/async_client.py +++ /dev/null @@ -1,591 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import 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.shopping.merchant_inventories_v1beta 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.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - - -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.shopping.merchant_inventories_v1beta.services.local_inventory_service import pagers -from google.shopping.merchant_inventories_v1beta.types import localinventory -from google.shopping.type.types import types -from google.type import interval_pb2 # type: ignore -from .transports.base import LocalInventoryServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import LocalInventoryServiceGrpcAsyncIOTransport -from .client import LocalInventoryServiceClient - -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 LocalInventoryServiceAsyncClient: - """Service to manage local inventory for products""" - - _client: LocalInventoryServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = LocalInventoryServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = LocalInventoryServiceClient._DEFAULT_UNIVERSE - - local_inventory_path = staticmethod(LocalInventoryServiceClient.local_inventory_path) - parse_local_inventory_path = staticmethod(LocalInventoryServiceClient.parse_local_inventory_path) - common_billing_account_path = staticmethod(LocalInventoryServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(LocalInventoryServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(LocalInventoryServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(LocalInventoryServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(LocalInventoryServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(LocalInventoryServiceClient.parse_common_organization_path) - common_project_path = staticmethod(LocalInventoryServiceClient.common_project_path) - parse_common_project_path = staticmethod(LocalInventoryServiceClient.parse_common_project_path) - common_location_path = staticmethod(LocalInventoryServiceClient.common_location_path) - parse_common_location_path = staticmethod(LocalInventoryServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - LocalInventoryServiceAsyncClient: The constructed client. - """ - return LocalInventoryServiceClient.from_service_account_info.__func__(LocalInventoryServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - LocalInventoryServiceAsyncClient: The constructed client. - """ - return LocalInventoryServiceClient.from_service_account_file.__func__(LocalInventoryServiceAsyncClient, 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): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return LocalInventoryServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> LocalInventoryServiceTransport: - """Returns the transport used by the client instance. - - Returns: - LocalInventoryServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._client._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used - by the client instance. - """ - return self._client._universe_domain - - get_transport_class = LocalInventoryServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, LocalInventoryServiceTransport, Callable[..., LocalInventoryServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the local inventory service async client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,LocalInventoryServiceTransport,Callable[..., LocalInventoryServiceTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport to use. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the LocalInventoryServiceTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = LocalInventoryServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.shopping.merchant.inventories_v1beta.LocalInventoryServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), - "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { - "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "credentialsType": None, - } - ) - - async def list_local_inventories(self, - request: Optional[Union[localinventory.ListLocalInventoriesRequest, 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.ListLocalInventoriesAsyncPager: - r"""Lists the ``LocalInventory`` resources for the given product in - your merchant account. The response might contain fewer items - than specified by ``pageSize``. If ``pageToken`` was returned in - previous request, it can be used to obtain additional results. - - ``LocalInventory`` resources are listed per product for a given - account. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_inventories_v1beta - - async def sample_list_local_inventories(): - # Create a client - client = merchant_inventories_v1beta.LocalInventoryServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.ListLocalInventoriesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_local_inventories(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesRequest, dict]]): - The request object. Request message for the ``ListLocalInventories`` method. - parent (:class:`str`): - Required. The ``name`` of the parent product to list - local inventories for. Format: - ``accounts/{account}/products/{product}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.shopping.merchant_inventories_v1beta.services.local_inventory_service.pagers.ListLocalInventoriesAsyncPager: - Response message for the ListLocalInventories method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, localinventory.ListLocalInventoriesRequest): - request = localinventory.ListLocalInventoriesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_local_inventories] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListLocalInventoriesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def insert_local_inventory(self, - request: Optional[Union[localinventory.InsertLocalInventoryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> localinventory.LocalInventory: - r"""Inserts a ``LocalInventory`` resource to a product in your - merchant account. - - Replaces the full ``LocalInventory`` resource if an entry with - the same - [``storeCode``][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code] - already exists for the product. - - It might take up to 30 minutes for the new or updated - ``LocalInventory`` resource to appear in products. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_inventories_v1beta - - async def sample_insert_local_inventory(): - # Create a client - client = merchant_inventories_v1beta.LocalInventoryServiceAsyncClient() - - # Initialize request argument(s) - local_inventory = merchant_inventories_v1beta.LocalInventory() - local_inventory.store_code = "store_code_value" - - request = merchant_inventories_v1beta.InsertLocalInventoryRequest( - parent="parent_value", - local_inventory=local_inventory, - ) - - # Make the request - response = await client.insert_local_inventory(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_inventories_v1beta.types.InsertLocalInventoryRequest, dict]]): - The request object. Request message for the ``InsertLocalInventory`` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.shopping.merchant_inventories_v1beta.types.LocalInventory: - Local inventory information for the product. Represents in-store information - for a specific product at the store specified by - [storeCode][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code]. - For a list of all accepted attribute values, see the - [local product inventory data - specification](\ https://support.google.com/merchants/answer/3061342). - - """ - # Create or coerce a protobuf request object. - # - 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, localinventory.InsertLocalInventoryRequest): - request = localinventory.InsertLocalInventoryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.insert_local_inventory] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_local_inventory(self, - request: Optional[Union[localinventory.DeleteLocalInventoryRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes the specified ``LocalInventory`` from the given product - in your merchant account. It might take a up to an hour for the - ``LocalInventory`` to be deleted from the specific product. Once - you have received a successful delete response, wait for that - period before attempting a delete again. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_inventories_v1beta - - async def sample_delete_local_inventory(): - # Create a client - client = merchant_inventories_v1beta.LocalInventoryServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.DeleteLocalInventoryRequest( - name="name_value", - ) - - # Make the request - await client.delete_local_inventory(request=request) - - Args: - request (Optional[Union[google.shopping.merchant_inventories_v1beta.types.DeleteLocalInventoryRequest, dict]]): - The request object. Request message for the ``DeleteLocalInventory`` method. - name (:class:`str`): - Required. The name of the local inventory for the given - product to delete. Format: - ``accounts/{account}/products/{product}/localInventories/{store_code}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, localinventory.DeleteLocalInventoryRequest): - request = localinventory.DeleteLocalInventoryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_local_inventory] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def __aenter__(self) -> "LocalInventoryServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER - DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -__all__ = ( - "LocalInventoryServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/client.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/client.py deleted file mode 100644 index 0e39530e77d2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/client.py +++ /dev/null @@ -1,950 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from http import HTTPStatus -import json -import logging as std_logging -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.shopping.merchant_inventories_v1beta 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.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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -from google.shopping.merchant_inventories_v1beta.services.local_inventory_service import pagers -from google.shopping.merchant_inventories_v1beta.types import localinventory -from google.shopping.type.types import types -from google.type import interval_pb2 # type: ignore -from .transports.base import LocalInventoryServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import LocalInventoryServiceGrpcTransport -from .transports.grpc_asyncio import LocalInventoryServiceGrpcAsyncIOTransport -from .transports.rest import LocalInventoryServiceRestTransport - - -class LocalInventoryServiceClientMeta(type): - """Metaclass for the LocalInventoryService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[LocalInventoryServiceTransport]] - _transport_registry["grpc"] = LocalInventoryServiceGrpcTransport - _transport_registry["grpc_asyncio"] = LocalInventoryServiceGrpcAsyncIOTransport - _transport_registry["rest"] = LocalInventoryServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[LocalInventoryServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class LocalInventoryServiceClient(metaclass=LocalInventoryServiceClientMeta): - """Service to manage local inventory for products""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = "merchantapi.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "merchantapi.{UNIVERSE_DOMAIN}" - _DEFAULT_UNIVERSE = "googleapis.com" - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - LocalInventoryServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - LocalInventoryServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> LocalInventoryServiceTransport: - """Returns the transport used by the client instance. - - Returns: - LocalInventoryServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def local_inventory_path(account: str,product: str,store_code: str,) -> str: - """Returns a fully-qualified local_inventory string.""" - return "accounts/{account}/products/{product}/localInventories/{store_code}".format(account=account, product=product, store_code=store_code, ) - - @staticmethod - def parse_local_inventory_path(path: str) -> Dict[str,str]: - """Parses a local_inventory path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/products/(?P.+?)/localInventories/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - 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: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - 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) - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "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 - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_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): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = LocalInventoryServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = LocalInventoryServiceClient._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: - """Return the universe domain used by the client. - - Args: - client_universe_domain (Optional[str]): The universe domain configured via the client options. - universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. - - Returns: - str: The universe domain to be used by the client. - - Raises: - ValueError: If the universe domain is an empty string. - """ - universe_domain = LocalInventoryServiceClient._DEFAULT_UNIVERSE - if client_universe_domain is not None: - universe_domain = client_universe_domain - elif universe_domain_env is not None: - universe_domain = universe_domain_env - if len(universe_domain.strip()) == 0: - raise ValueError("Universe Domain cannot be an empty string.") - return universe_domain - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - - # NOTE (b/349488459): universe validation is disabled until further notice. - return True - - def _add_cred_info_for_auth_errors( - 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]: - return - - cred = self._transport._credentials - - # get_cred_info is only available in google-auth>=2.35.0 - if not hasattr(cred, "get_cred_info"): - return - - # ignore the type check since pypy test fails when get_cred_info - # is not available - cred_info = cred.get_cred_info() # type: ignore - if cred_info and hasattr(error._details, "append"): - error._details.append(json.dumps(cred_info)) - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, LocalInventoryServiceTransport, Callable[..., LocalInventoryServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the local inventory service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,LocalInventoryServiceTransport,Callable[..., LocalInventoryServiceTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the LocalInventoryServiceTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - 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) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = LocalInventoryServiceClient._read_environment_variables() - self._client_cert_source = LocalInventoryServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = LocalInventoryServiceClient._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 - - if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER - # Setup logging. - client_logging.initialize_logging() - - 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") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - transport_provided = isinstance(transport, LocalInventoryServiceTransport) - if transport_provided: - # transport is a LocalInventoryServiceTransport instance. - if credentials or self._client_options.credentials_file or api_key_value: - 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." - ) - self._transport = cast(LocalInventoryServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - LocalInventoryServiceClient._get_api_endpoint( - self._client_options.api_endpoint, - self._client_cert_source, - self._universe_domain, - 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) - - transport_init: Union[Type[LocalInventoryServiceTransport], Callable[..., LocalInventoryServiceTransport]] = ( - LocalInventoryServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., LocalInventoryServiceTransport], transport) - ) - # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) - - if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "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 { - "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "credentialsType": None, - } - ) - - def list_local_inventories(self, - request: Optional[Union[localinventory.ListLocalInventoriesRequest, 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.ListLocalInventoriesPager: - r"""Lists the ``LocalInventory`` resources for the given product in - your merchant account. The response might contain fewer items - than specified by ``pageSize``. If ``pageToken`` was returned in - previous request, it can be used to obtain additional results. - - ``LocalInventory`` resources are listed per product for a given - account. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_inventories_v1beta - - def sample_list_local_inventories(): - # Create a client - client = merchant_inventories_v1beta.LocalInventoryServiceClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.ListLocalInventoriesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_local_inventories(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesRequest, dict]): - The request object. Request message for the ``ListLocalInventories`` method. - parent (str): - Required. The ``name`` of the parent product to list - local inventories for. Format: - ``accounts/{account}/products/{product}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.shopping.merchant_inventories_v1beta.services.local_inventory_service.pagers.ListLocalInventoriesPager: - Response message for the ListLocalInventories method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, localinventory.ListLocalInventoriesRequest): - request = localinventory.ListLocalInventoriesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_local_inventories] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListLocalInventoriesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def insert_local_inventory(self, - request: Optional[Union[localinventory.InsertLocalInventoryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> localinventory.LocalInventory: - r"""Inserts a ``LocalInventory`` resource to a product in your - merchant account. - - Replaces the full ``LocalInventory`` resource if an entry with - the same - [``storeCode``][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code] - already exists for the product. - - It might take up to 30 minutes for the new or updated - ``LocalInventory`` resource to appear in products. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_inventories_v1beta - - def sample_insert_local_inventory(): - # Create a client - client = merchant_inventories_v1beta.LocalInventoryServiceClient() - - # Initialize request argument(s) - local_inventory = merchant_inventories_v1beta.LocalInventory() - local_inventory.store_code = "store_code_value" - - request = merchant_inventories_v1beta.InsertLocalInventoryRequest( - parent="parent_value", - local_inventory=local_inventory, - ) - - # Make the request - response = client.insert_local_inventory(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_inventories_v1beta.types.InsertLocalInventoryRequest, dict]): - The request object. Request message for the ``InsertLocalInventory`` 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: - google.shopping.merchant_inventories_v1beta.types.LocalInventory: - Local inventory information for the product. Represents in-store information - for a specific product at the store specified by - [storeCode][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code]. - For a list of all accepted attribute values, see the - [local product inventory data - specification](\ https://support.google.com/merchants/answer/3061342). - - """ - # Create or coerce a protobuf request object. - # - 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, localinventory.InsertLocalInventoryRequest): - request = localinventory.InsertLocalInventoryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.insert_local_inventory] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_local_inventory(self, - request: Optional[Union[localinventory.DeleteLocalInventoryRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes the specified ``LocalInventory`` from the given product - in your merchant account. It might take a up to an hour for the - ``LocalInventory`` to be deleted from the specific product. Once - you have received a successful delete response, wait for that - period before attempting a delete again. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_inventories_v1beta - - def sample_delete_local_inventory(): - # Create a client - client = merchant_inventories_v1beta.LocalInventoryServiceClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.DeleteLocalInventoryRequest( - name="name_value", - ) - - # Make the request - client.delete_local_inventory(request=request) - - Args: - request (Union[google.shopping.merchant_inventories_v1beta.types.DeleteLocalInventoryRequest, dict]): - The request object. Request message for the ``DeleteLocalInventory`` method. - name (str): - Required. The name of the local inventory for the given - product to delete. Format: - ``accounts/{account}/products/{product}/localInventories/{store_code}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, localinventory.DeleteLocalInventoryRequest): - request = localinventory.DeleteLocalInventoryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_local_inventory] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def __enter__(self) -> "LocalInventoryServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER - DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - -__all__ = ( - "LocalInventoryServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/pagers.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/pagers.py deleted file mode 100644 index 047973fdb67b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/pagers.py +++ /dev/null @@ -1,166 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from 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] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore - -from google.shopping.merchant_inventories_v1beta.types import localinventory - - -class ListLocalInventoriesPager: - """A pager for iterating through ``list_local_inventories`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``local_inventories`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListLocalInventories`` requests and continue to iterate - through the ``local_inventories`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesResponse` - 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[..., localinventory.ListLocalInventoriesResponse], - request: localinventory.ListLocalInventoriesRequest, - response: localinventory.ListLocalInventoriesResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesRequest): - The initial request object. - response (google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = localinventory.ListLocalInventoriesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[localinventory.ListLocalInventoriesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[localinventory.LocalInventory]: - for page in self.pages: - yield from page.local_inventories - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListLocalInventoriesAsyncPager: - """A pager for iterating through ``list_local_inventories`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``local_inventories`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListLocalInventories`` requests and continue to iterate - through the ``local_inventories`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesResponse` - 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[localinventory.ListLocalInventoriesResponse]], - request: localinventory.ListLocalInventoriesRequest, - response: localinventory.ListLocalInventoriesResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesRequest): - The initial request object. - response (google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = localinventory.ListLocalInventoriesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[localinventory.ListLocalInventoriesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[localinventory.LocalInventory]: - async def async_generator(): - async for page in self.pages: - for response in page.local_inventories: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/README.rst deleted file mode 100644 index 816e98eb5847..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`LocalInventoryServiceTransport` is the ABC for all transports. -- public child `LocalInventoryServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `LocalInventoryServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseLocalInventoryServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `LocalInventoryServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/__init__.py deleted file mode 100644 index e1c84f7bce12..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import LocalInventoryServiceTransport -from .grpc import LocalInventoryServiceGrpcTransport -from .grpc_asyncio import LocalInventoryServiceGrpcAsyncIOTransport -from .rest import LocalInventoryServiceRestTransport -from .rest import LocalInventoryServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[LocalInventoryServiceTransport]] -_transport_registry['grpc'] = LocalInventoryServiceGrpcTransport -_transport_registry['grpc_asyncio'] = LocalInventoryServiceGrpcAsyncIOTransport -_transport_registry['rest'] = LocalInventoryServiceRestTransport - -__all__ = ( - 'LocalInventoryServiceTransport', - 'LocalInventoryServiceGrpcTransport', - 'LocalInventoryServiceGrpcAsyncIOTransport', - 'LocalInventoryServiceRestTransport', - 'LocalInventoryServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/base.py deleted file mode 100644 index df3eb9afd0a3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/base.py +++ /dev/null @@ -1,188 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.shopping.merchant_inventories_v1beta 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 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - -from google.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_inventories_v1beta.types import localinventory - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER - DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -class LocalInventoryServiceTransport(abc.ABC): - """Abstract transport class for LocalInventoryService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/content', - ) - - DEFAULT_HOST: str = 'merchantapi.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: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'merchantapi.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - if not hasattr(self, "_ignore_credentials"): - self._ignore_credentials: bool = False - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_local_inventories: gapic_v1.method.wrap_method( - self.list_local_inventories, - default_timeout=None, - client_info=client_info, - ), - self.insert_local_inventory: gapic_v1.method.wrap_method( - self.insert_local_inventory, - default_timeout=None, - client_info=client_info, - ), - self.delete_local_inventory: gapic_v1.method.wrap_method( - self.delete_local_inventory, - 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! - """ - raise NotImplementedError() - - @property - def list_local_inventories(self) -> Callable[ - [localinventory.ListLocalInventoriesRequest], - Union[ - localinventory.ListLocalInventoriesResponse, - Awaitable[localinventory.ListLocalInventoriesResponse] - ]]: - raise NotImplementedError() - - @property - def insert_local_inventory(self) -> Callable[ - [localinventory.InsertLocalInventoryRequest], - Union[ - localinventory.LocalInventory, - Awaitable[localinventory.LocalInventory] - ]]: - raise NotImplementedError() - - @property - def delete_local_inventory(self) -> Callable[ - [localinventory.DeleteLocalInventoryRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'LocalInventoryServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc.py deleted file mode 100644 index fd453f2f86bd..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc.py +++ /dev/null @@ -1,418 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import json -import logging as std_logging -import pickle -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 - -from google.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_inventories_v1beta.types import localinventory -from .base import LocalInventoryServiceTransport, 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 - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER - def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "rpcName": str(client_call_details.method), - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - response = continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = response.result() - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response for {client_call_details.method}.", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class LocalInventoryServiceGrpcTransport(LocalInventoryServiceTransport): - """gRPC backend transport for LocalInventoryService. - - Service to manage local inventory for products - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'merchantapi.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: - host (Optional[str]): - The hostname to connect to (default: 'merchantapi.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if a ``channel`` instance is provided. - channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, grpc.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) - - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'merchantapi.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. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_local_inventories(self) -> Callable[ - [localinventory.ListLocalInventoriesRequest], - localinventory.ListLocalInventoriesResponse]: - r"""Return a callable for the list local inventories method over gRPC. - - Lists the ``LocalInventory`` resources for the given product in - your merchant account. The response might contain fewer items - than specified by ``pageSize``. If ``pageToken`` was returned in - previous request, it can be used to obtain additional results. - - ``LocalInventory`` resources are listed per product for a given - account. - - Returns: - Callable[[~.ListLocalInventoriesRequest], - ~.ListLocalInventoriesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_local_inventories' not in self._stubs: - self._stubs['list_local_inventories'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1beta.LocalInventoryService/ListLocalInventories', - request_serializer=localinventory.ListLocalInventoriesRequest.serialize, - response_deserializer=localinventory.ListLocalInventoriesResponse.deserialize, - ) - return self._stubs['list_local_inventories'] - - @property - def insert_local_inventory(self) -> Callable[ - [localinventory.InsertLocalInventoryRequest], - localinventory.LocalInventory]: - r"""Return a callable for the insert local inventory method over gRPC. - - Inserts a ``LocalInventory`` resource to a product in your - merchant account. - - Replaces the full ``LocalInventory`` resource if an entry with - the same - [``storeCode``][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code] - already exists for the product. - - It might take up to 30 minutes for the new or updated - ``LocalInventory`` resource to appear in products. - - Returns: - Callable[[~.InsertLocalInventoryRequest], - ~.LocalInventory]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'insert_local_inventory' not in self._stubs: - self._stubs['insert_local_inventory'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1beta.LocalInventoryService/InsertLocalInventory', - request_serializer=localinventory.InsertLocalInventoryRequest.serialize, - response_deserializer=localinventory.LocalInventory.deserialize, - ) - return self._stubs['insert_local_inventory'] - - @property - def delete_local_inventory(self) -> Callable[ - [localinventory.DeleteLocalInventoryRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete local inventory method over gRPC. - - Deletes the specified ``LocalInventory`` from the given product - in your merchant account. It might take a up to an hour for the - ``LocalInventory`` to be deleted from the specific product. Once - you have received a successful delete response, wait for that - period before attempting a delete again. - - Returns: - Callable[[~.DeleteLocalInventoryRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_local_inventory' not in self._stubs: - self._stubs['delete_local_inventory'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1beta.LocalInventoryService/DeleteLocalInventory', - request_serializer=localinventory.DeleteLocalInventoryRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_local_inventory'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'LocalInventoryServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc_asyncio.py deleted file mode 100644 index 8e11b62a9522..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,449 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import inspect -import json -import pickle -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 retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.protobuf.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.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_inventories_v1beta.types import localinventory -from .base import LocalInventoryServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import LocalInventoryServiceGrpcTransport - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER - async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "rpcName": str(client_call_details.method), - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - response = await continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = await response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = await response - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response to rpc {client_call_details.method}.", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class LocalInventoryServiceGrpcAsyncIOTransport(LocalInventoryServiceTransport): - """gRPC AsyncIO backend transport for LocalInventoryService. - - Service to manage local inventory for products - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'merchantapi.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. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'merchantapi.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: - host (Optional[str]): - The hostname to connect to (default: 'merchantapi.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, aio.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientAIOInterceptor() - self._grpc_channel._unary_unary_interceptors.append(self._interceptor) - self._logged_channel = self._grpc_channel - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_local_inventories(self) -> Callable[ - [localinventory.ListLocalInventoriesRequest], - Awaitable[localinventory.ListLocalInventoriesResponse]]: - r"""Return a callable for the list local inventories method over gRPC. - - Lists the ``LocalInventory`` resources for the given product in - your merchant account. The response might contain fewer items - than specified by ``pageSize``. If ``pageToken`` was returned in - previous request, it can be used to obtain additional results. - - ``LocalInventory`` resources are listed per product for a given - account. - - Returns: - Callable[[~.ListLocalInventoriesRequest], - Awaitable[~.ListLocalInventoriesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_local_inventories' not in self._stubs: - self._stubs['list_local_inventories'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1beta.LocalInventoryService/ListLocalInventories', - request_serializer=localinventory.ListLocalInventoriesRequest.serialize, - response_deserializer=localinventory.ListLocalInventoriesResponse.deserialize, - ) - return self._stubs['list_local_inventories'] - - @property - def insert_local_inventory(self) -> Callable[ - [localinventory.InsertLocalInventoryRequest], - Awaitable[localinventory.LocalInventory]]: - r"""Return a callable for the insert local inventory method over gRPC. - - Inserts a ``LocalInventory`` resource to a product in your - merchant account. - - Replaces the full ``LocalInventory`` resource if an entry with - the same - [``storeCode``][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code] - already exists for the product. - - It might take up to 30 minutes for the new or updated - ``LocalInventory`` resource to appear in products. - - Returns: - Callable[[~.InsertLocalInventoryRequest], - Awaitable[~.LocalInventory]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'insert_local_inventory' not in self._stubs: - self._stubs['insert_local_inventory'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1beta.LocalInventoryService/InsertLocalInventory', - request_serializer=localinventory.InsertLocalInventoryRequest.serialize, - response_deserializer=localinventory.LocalInventory.deserialize, - ) - return self._stubs['insert_local_inventory'] - - @property - def delete_local_inventory(self) -> Callable[ - [localinventory.DeleteLocalInventoryRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete local inventory method over gRPC. - - Deletes the specified ``LocalInventory`` from the given product - in your merchant account. It might take a up to an hour for the - ``LocalInventory`` to be deleted from the specific product. Once - you have received a successful delete response, wait for that - period before attempting a delete again. - - Returns: - Callable[[~.DeleteLocalInventoryRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_local_inventory' not in self._stubs: - self._stubs['delete_local_inventory'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1beta.LocalInventoryService/DeleteLocalInventory', - request_serializer=localinventory.DeleteLocalInventoryRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_local_inventory'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.list_local_inventories: self._wrap_method( - self.list_local_inventories, - default_timeout=None, - client_info=client_info, - ), - self.insert_local_inventory: self._wrap_method( - self.insert_local_inventory, - default_timeout=None, - client_info=client_info, - ), - self.delete_local_inventory: self._wrap_method( - self.delete_local_inventory, - default_timeout=None, - client_info=client_info, - ), - } - - def _wrap_method(self, func, *args, **kwargs): - if self._wrap_with_kind: # pragma: NO COVER - kwargs["kind"] = self.kind - return gapic_v1.method_async.wrap_method(func, *args, **kwargs) - - def close(self): - return self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - -__all__ = ( - 'LocalInventoryServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest.py deleted file mode 100644 index 651ae59e98d5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest.py +++ /dev/null @@ -1,640 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import 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 warnings - - -from google.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_inventories_v1beta.types import localinventory - - -from .rest_base import _BaseLocalInventoryServiceRestTransport -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = logging.getLogger(__name__) - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=f"requests@{requests_version}", -) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER - DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -class LocalInventoryServiceRestInterceptor: - """Interceptor for LocalInventoryService. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the LocalInventoryServiceRestTransport. - - .. code-block:: python - class MyCustomLocalInventoryServiceInterceptor(LocalInventoryServiceRestInterceptor): - def pre_delete_local_inventory(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_insert_local_inventory(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_insert_local_inventory(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_local_inventories(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_local_inventories(self, response): - logging.log(f"Received response: {response}") - return response - - transport = LocalInventoryServiceRestTransport(interceptor=MyCustomLocalInventoryServiceInterceptor()) - client = LocalInventoryServiceClient(transport=transport) - - - """ - def pre_delete_local_inventory(self, request: localinventory.DeleteLocalInventoryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[localinventory.DeleteLocalInventoryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_local_inventory - - Override in a subclass to manipulate the request or metadata - before they are sent to the LocalInventoryService server. - """ - return request, metadata - - def pre_insert_local_inventory(self, request: localinventory.InsertLocalInventoryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[localinventory.InsertLocalInventoryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for insert_local_inventory - - Override in a subclass to manipulate the request or metadata - before they are sent to the LocalInventoryService server. - """ - return request, metadata - - def post_insert_local_inventory(self, response: localinventory.LocalInventory) -> localinventory.LocalInventory: - """Post-rpc interceptor for insert_local_inventory - - DEPRECATED. Please use the `post_insert_local_inventory_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the LocalInventoryService server but before - it is returned to user code. This `post_insert_local_inventory` interceptor runs - before the `post_insert_local_inventory_with_metadata` interceptor. - """ - return response - - def post_insert_local_inventory_with_metadata(self, response: localinventory.LocalInventory, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[localinventory.LocalInventory, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for insert_local_inventory - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the LocalInventoryService server but before it is returned to user code. - - We recommend only using this `post_insert_local_inventory_with_metadata` - interceptor in new development instead of the `post_insert_local_inventory` interceptor. - When both interceptors are used, this `post_insert_local_inventory_with_metadata` interceptor runs after the - `post_insert_local_inventory` interceptor. The (possibly modified) response returned by - `post_insert_local_inventory` will be passed to - `post_insert_local_inventory_with_metadata`. - """ - return response, metadata - - def pre_list_local_inventories(self, request: localinventory.ListLocalInventoriesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[localinventory.ListLocalInventoriesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_local_inventories - - Override in a subclass to manipulate the request or metadata - before they are sent to the LocalInventoryService server. - """ - return request, metadata - - def post_list_local_inventories(self, response: localinventory.ListLocalInventoriesResponse) -> localinventory.ListLocalInventoriesResponse: - """Post-rpc interceptor for list_local_inventories - - DEPRECATED. Please use the `post_list_local_inventories_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the LocalInventoryService server but before - it is returned to user code. This `post_list_local_inventories` interceptor runs - before the `post_list_local_inventories_with_metadata` interceptor. - """ - return response - - def post_list_local_inventories_with_metadata(self, response: localinventory.ListLocalInventoriesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[localinventory.ListLocalInventoriesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_local_inventories - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the LocalInventoryService server but before it is returned to user code. - - We recommend only using this `post_list_local_inventories_with_metadata` - interceptor in new development instead of the `post_list_local_inventories` interceptor. - When both interceptors are used, this `post_list_local_inventories_with_metadata` interceptor runs after the - `post_list_local_inventories` interceptor. The (possibly modified) response returned by - `post_list_local_inventories` will be passed to - `post_list_local_inventories_with_metadata`. - """ - return response, metadata - - -@dataclasses.dataclass -class LocalInventoryServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: LocalInventoryServiceRestInterceptor - - -class LocalInventoryServiceRestTransport(_BaseLocalInventoryServiceRestTransport): - """REST backend synchronous transport for LocalInventoryService. - - Service to manage local inventory for products - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'merchantapi.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[LocalInventoryServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'merchantapi.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - url_scheme=url_scheme, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or LocalInventoryServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _DeleteLocalInventory(_BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory, LocalInventoryServiceRestStub): - def __hash__(self): - return hash("LocalInventoryServiceRestTransport.DeleteLocalInventory") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: localinventory.DeleteLocalInventoryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): - r"""Call the delete local inventory method over HTTP. - - Args: - request (~.localinventory.DeleteLocalInventoryRequest): - The request object. Request message for the ``DeleteLocalInventory`` 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 = _BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._get_http_options() - - request, metadata = self._interceptor.pre_delete_local_inventory(request, metadata) - transcoded_request = _BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient.DeleteLocalInventory", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "rpcName": "DeleteLocalInventory", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = LocalInventoryServiceRestTransport._DeleteLocalInventory._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 _InsertLocalInventory(_BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory, LocalInventoryServiceRestStub): - def __hash__(self): - return hash("LocalInventoryServiceRestTransport.InsertLocalInventory") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: localinventory.InsertLocalInventoryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> localinventory.LocalInventory: - r"""Call the insert local inventory method over HTTP. - - Args: - request (~.localinventory.InsertLocalInventoryRequest): - The request object. Request message for the ``InsertLocalInventory`` 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: - ~.localinventory.LocalInventory: - Local inventory information for the product. Represents - in-store information for a specific product at the store - specified by - [``storeCode``][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code]. - For a list of all accepted attribute values, see the - `local product inventory data - specification `__. - - """ - - http_options = _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_http_options() - - request, metadata = self._interceptor.pre_insert_local_inventory(request, metadata) - transcoded_request = _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_transcoded_request(http_options, request) - - body = _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient.InsertLocalInventory", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "rpcName": "InsertLocalInventory", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = LocalInventoryServiceRestTransport._InsertLocalInventory._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = localinventory.LocalInventory() - pb_resp = localinventory.LocalInventory.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_insert_local_inventory(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_insert_local_inventory_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = localinventory.LocalInventory.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient.insert_local_inventory", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "rpcName": "InsertLocalInventory", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListLocalInventories(_BaseLocalInventoryServiceRestTransport._BaseListLocalInventories, LocalInventoryServiceRestStub): - def __hash__(self): - return hash("LocalInventoryServiceRestTransport.ListLocalInventories") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: localinventory.ListLocalInventoriesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> localinventory.ListLocalInventoriesResponse: - r"""Call the list local inventories method over HTTP. - - Args: - request (~.localinventory.ListLocalInventoriesRequest): - The request object. Request message for the ``ListLocalInventories`` 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: - ~.localinventory.ListLocalInventoriesResponse: - Response message for the ``ListLocalInventories`` - method. - - """ - - http_options = _BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._get_http_options() - - request, metadata = self._interceptor.pre_list_local_inventories(request, metadata) - transcoded_request = _BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient.ListLocalInventories", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "rpcName": "ListLocalInventories", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = LocalInventoryServiceRestTransport._ListLocalInventories._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = localinventory.ListLocalInventoriesResponse() - pb_resp = localinventory.ListLocalInventoriesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_local_inventories(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_local_inventories_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = localinventory.ListLocalInventoriesResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.shopping.merchant.inventories_v1beta.LocalInventoryServiceClient.list_local_inventories", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "rpcName": "ListLocalInventories", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def delete_local_inventory(self) -> Callable[ - [localinventory.DeleteLocalInventoryRequest], - 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._DeleteLocalInventory(self._session, self._host, self._interceptor) # type: ignore - - @property - def insert_local_inventory(self) -> Callable[ - [localinventory.InsertLocalInventoryRequest], - localinventory.LocalInventory]: - # 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._InsertLocalInventory(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_local_inventories(self) -> Callable[ - [localinventory.ListLocalInventoriesRequest], - localinventory.ListLocalInventoriesResponse]: - # 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._ListLocalInventories(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'LocalInventoryServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest_base.py deleted file mode 100644 index 0394bb42ce48..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/local_inventory_service/transports/rest_base.py +++ /dev/null @@ -1,213 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import json # type: ignore -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from .base import LocalInventoryServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_inventories_v1beta.types import localinventory - - -class _BaseLocalInventoryServiceRestTransport(LocalInventoryServiceTransport): - """Base REST backend transport for LocalInventoryService. - - Note: This class is not meant to be used directly. Use its sync and - async sub-classes instead. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'merchantapi.googleapis.com', - credentials: Optional[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - Args: - host (Optional[str]): - The hostname to connect to (default: 'merchantapi.googleapis.com'). - credentials (Optional[Any]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - - class _BaseDeleteLocalInventory: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/inventories/v1beta/{name=accounts/*/products/*/localInventories/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = localinventory.DeleteLocalInventoryRequest.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(_BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseInsertLocalInventory: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/inventories/v1beta/{parent=accounts/*/products/*}/localInventories:insert', - 'body': 'local_inventory', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = localinventory.InsertLocalInventoryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListLocalInventories: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/inventories/v1beta/{parent=accounts/*/products/*}/localInventories', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = localinventory.ListLocalInventoriesRequest.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(_BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseLocalInventoryServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/__init__.py deleted file mode 100644 index 1a0839e5cff5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import RegionalInventoryServiceClient -from .async_client import RegionalInventoryServiceAsyncClient - -__all__ = ( - 'RegionalInventoryServiceClient', - 'RegionalInventoryServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/async_client.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/async_client.py deleted file mode 100644 index e041a2099942..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/async_client.py +++ /dev/null @@ -1,597 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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.shopping.merchant_inventories_v1beta 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.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - - -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.shopping.merchant_inventories_v1beta.services.regional_inventory_service import pagers -from google.shopping.merchant_inventories_v1beta.types import regionalinventory -from google.shopping.type.types import types -from google.type import interval_pb2 # type: ignore -from .transports.base import RegionalInventoryServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import RegionalInventoryServiceGrpcAsyncIOTransport -from .client import RegionalInventoryServiceClient - -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 RegionalInventoryServiceAsyncClient: - """Service to manage regional inventory for products. There is also - separate ``regions`` resource and API to manage regions definitions. - """ - - _client: RegionalInventoryServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = RegionalInventoryServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = RegionalInventoryServiceClient._DEFAULT_UNIVERSE - - regional_inventory_path = staticmethod(RegionalInventoryServiceClient.regional_inventory_path) - parse_regional_inventory_path = staticmethod(RegionalInventoryServiceClient.parse_regional_inventory_path) - common_billing_account_path = staticmethod(RegionalInventoryServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(RegionalInventoryServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(RegionalInventoryServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(RegionalInventoryServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(RegionalInventoryServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(RegionalInventoryServiceClient.parse_common_organization_path) - common_project_path = staticmethod(RegionalInventoryServiceClient.common_project_path) - parse_common_project_path = staticmethod(RegionalInventoryServiceClient.parse_common_project_path) - common_location_path = staticmethod(RegionalInventoryServiceClient.common_location_path) - parse_common_location_path = staticmethod(RegionalInventoryServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RegionalInventoryServiceAsyncClient: The constructed client. - """ - return RegionalInventoryServiceClient.from_service_account_info.__func__(RegionalInventoryServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RegionalInventoryServiceAsyncClient: The constructed client. - """ - return RegionalInventoryServiceClient.from_service_account_file.__func__(RegionalInventoryServiceAsyncClient, 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): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return RegionalInventoryServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> RegionalInventoryServiceTransport: - """Returns the transport used by the client instance. - - Returns: - RegionalInventoryServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._client._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used - by the client instance. - """ - return self._client._universe_domain - - get_transport_class = RegionalInventoryServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, RegionalInventoryServiceTransport, Callable[..., RegionalInventoryServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the regional inventory service async client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,RegionalInventoryServiceTransport,Callable[..., RegionalInventoryServiceTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport to use. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the RegionalInventoryServiceTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = RegionalInventoryServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), - "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { - "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "credentialsType": None, - } - ) - - async def list_regional_inventories(self, - request: Optional[Union[regionalinventory.ListRegionalInventoriesRequest, 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.ListRegionalInventoriesAsyncPager: - r"""Lists the ``RegionalInventory`` resources for the given product - in your merchant account. The response might contain fewer items - than specified by ``pageSize``. If ``pageToken`` was returned in - previous request, it can be used to obtain additional results. - - ``RegionalInventory`` resources are listed per product for a - given account. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_inventories_v1beta - - async def sample_list_regional_inventories(): - # Create a client - client = merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.ListRegionalInventoriesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_regional_inventories(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesRequest, dict]]): - The request object. Request message for the ``ListRegionalInventories`` - method. - parent (:class:`str`): - Required. The ``name`` of the parent product to list - ``RegionalInventory`` resources for. Format: - ``accounts/{account}/products/{product}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.pagers.ListRegionalInventoriesAsyncPager: - Response message for the ListRegionalInventories method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, regionalinventory.ListRegionalInventoriesRequest): - request = regionalinventory.ListRegionalInventoriesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_regional_inventories] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListRegionalInventoriesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def insert_regional_inventory(self, - request: Optional[Union[regionalinventory.InsertRegionalInventoryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> regionalinventory.RegionalInventory: - r"""Inserts a ``RegionalInventory`` to a given product in your - merchant account. - - Replaces the full ``RegionalInventory`` resource if an entry - with the same - [``region``][google.shopping.merchant.inventories.v1beta.RegionalInventory.region] - already exists for the product. - - It might take up to 30 minutes for the new or updated - ``RegionalInventory`` resource to appear in products. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_inventories_v1beta - - async def sample_insert_regional_inventory(): - # Create a client - client = merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient() - - # Initialize request argument(s) - regional_inventory = merchant_inventories_v1beta.RegionalInventory() - regional_inventory.region = "region_value" - - request = merchant_inventories_v1beta.InsertRegionalInventoryRequest( - parent="parent_value", - regional_inventory=regional_inventory, - ) - - # Make the request - response = await client.insert_regional_inventory(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_inventories_v1beta.types.InsertRegionalInventoryRequest, dict]]): - The request object. Request message for the ``InsertRegionalInventory`` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.shopping.merchant_inventories_v1beta.types.RegionalInventory: - Regional inventory information for the product. Represents specific - information like price and availability for a given - product in a specific - [region][google.shopping.merchant.inventories.v1beta.RegionalInventory.region]. - For a list of all accepted attribute values, see the - [regional product inventory data - specification](\ https://support.google.com/merchants/answer/9698880). - - """ - # Create or coerce a protobuf request object. - # - 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, regionalinventory.InsertRegionalInventoryRequest): - request = regionalinventory.InsertRegionalInventoryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.insert_regional_inventory] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_regional_inventory(self, - request: Optional[Union[regionalinventory.DeleteRegionalInventoryRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes the specified ``RegionalInventory`` resource from the - given product in your merchant account. It might take up to an - hour for the ``RegionalInventory`` to be deleted from the - specific product. Once you have received a successful delete - response, wait for that period before attempting a delete again. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_inventories_v1beta - - async def sample_delete_regional_inventory(): - # Create a client - client = merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.DeleteRegionalInventoryRequest( - name="name_value", - ) - - # Make the request - await client.delete_regional_inventory(request=request) - - Args: - request (Optional[Union[google.shopping.merchant_inventories_v1beta.types.DeleteRegionalInventoryRequest, dict]]): - The request object. Request message for the ``DeleteRegionalInventory`` - method. - name (:class:`str`): - Required. The name of the ``RegionalInventory`` resource - to delete. Format: - ``accounts/{account}/products/{product}/regionalInventories/{region}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, regionalinventory.DeleteRegionalInventoryRequest): - request = regionalinventory.DeleteRegionalInventoryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_regional_inventory] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def __aenter__(self) -> "RegionalInventoryServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER - DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -__all__ = ( - "RegionalInventoryServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/client.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/client.py deleted file mode 100644 index 467abad899d0..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/client.py +++ /dev/null @@ -1,956 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from http import HTTPStatus -import json -import logging as std_logging -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.shopping.merchant_inventories_v1beta 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.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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service import pagers -from google.shopping.merchant_inventories_v1beta.types import regionalinventory -from google.shopping.type.types import types -from google.type import interval_pb2 # type: ignore -from .transports.base import RegionalInventoryServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import RegionalInventoryServiceGrpcTransport -from .transports.grpc_asyncio import RegionalInventoryServiceGrpcAsyncIOTransport -from .transports.rest import RegionalInventoryServiceRestTransport - - -class RegionalInventoryServiceClientMeta(type): - """Metaclass for the RegionalInventoryService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[RegionalInventoryServiceTransport]] - _transport_registry["grpc"] = RegionalInventoryServiceGrpcTransport - _transport_registry["grpc_asyncio"] = RegionalInventoryServiceGrpcAsyncIOTransport - _transport_registry["rest"] = RegionalInventoryServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[RegionalInventoryServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class RegionalInventoryServiceClient(metaclass=RegionalInventoryServiceClientMeta): - """Service to manage regional inventory for products. There is also - separate ``regions`` resource and API to manage regions definitions. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = "merchantapi.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "merchantapi.{UNIVERSE_DOMAIN}" - _DEFAULT_UNIVERSE = "googleapis.com" - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RegionalInventoryServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RegionalInventoryServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> RegionalInventoryServiceTransport: - """Returns the transport used by the client instance. - - Returns: - RegionalInventoryServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def regional_inventory_path(account: str,product: str,region: str,) -> str: - """Returns a fully-qualified regional_inventory string.""" - return "accounts/{account}/products/{product}/regionalInventories/{region}".format(account=account, product=product, region=region, ) - - @staticmethod - def parse_regional_inventory_path(path: str) -> Dict[str,str]: - """Parses a regional_inventory path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/products/(?P.+?)/regionalInventories/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - 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: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - 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) - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "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 - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_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): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = RegionalInventoryServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = RegionalInventoryServiceClient._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: - """Return the universe domain used by the client. - - Args: - client_universe_domain (Optional[str]): The universe domain configured via the client options. - universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. - - Returns: - str: The universe domain to be used by the client. - - Raises: - ValueError: If the universe domain is an empty string. - """ - universe_domain = RegionalInventoryServiceClient._DEFAULT_UNIVERSE - if client_universe_domain is not None: - universe_domain = client_universe_domain - elif universe_domain_env is not None: - universe_domain = universe_domain_env - if len(universe_domain.strip()) == 0: - raise ValueError("Universe Domain cannot be an empty string.") - return universe_domain - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - - # NOTE (b/349488459): universe validation is disabled until further notice. - return True - - def _add_cred_info_for_auth_errors( - 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]: - return - - cred = self._transport._credentials - - # get_cred_info is only available in google-auth>=2.35.0 - if not hasattr(cred, "get_cred_info"): - return - - # ignore the type check since pypy test fails when get_cred_info - # is not available - cred_info = cred.get_cred_info() # type: ignore - if cred_info and hasattr(error._details, "append"): - error._details.append(json.dumps(cred_info)) - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, RegionalInventoryServiceTransport, Callable[..., RegionalInventoryServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the regional inventory service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,RegionalInventoryServiceTransport,Callable[..., RegionalInventoryServiceTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the RegionalInventoryServiceTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - 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) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = RegionalInventoryServiceClient._read_environment_variables() - self._client_cert_source = RegionalInventoryServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = RegionalInventoryServiceClient._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 - - if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER - # Setup logging. - client_logging.initialize_logging() - - 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") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - transport_provided = isinstance(transport, RegionalInventoryServiceTransport) - if transport_provided: - # transport is a RegionalInventoryServiceTransport instance. - if credentials or self._client_options.credentials_file or api_key_value: - 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." - ) - self._transport = cast(RegionalInventoryServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - RegionalInventoryServiceClient._get_api_endpoint( - self._client_options.api_endpoint, - self._client_cert_source, - self._universe_domain, - 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) - - transport_init: Union[Type[RegionalInventoryServiceTransport], Callable[..., RegionalInventoryServiceTransport]] = ( - RegionalInventoryServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., RegionalInventoryServiceTransport], transport) - ) - # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) - - if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "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 { - "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "credentialsType": None, - } - ) - - def list_regional_inventories(self, - request: Optional[Union[regionalinventory.ListRegionalInventoriesRequest, 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.ListRegionalInventoriesPager: - r"""Lists the ``RegionalInventory`` resources for the given product - in your merchant account. The response might contain fewer items - than specified by ``pageSize``. If ``pageToken`` was returned in - previous request, it can be used to obtain additional results. - - ``RegionalInventory`` resources are listed per product for a - given account. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_inventories_v1beta - - def sample_list_regional_inventories(): - # Create a client - client = merchant_inventories_v1beta.RegionalInventoryServiceClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.ListRegionalInventoriesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_regional_inventories(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesRequest, dict]): - The request object. Request message for the ``ListRegionalInventories`` - method. - parent (str): - Required. The ``name`` of the parent product to list - ``RegionalInventory`` resources for. Format: - ``accounts/{account}/products/{product}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.pagers.ListRegionalInventoriesPager: - Response message for the ListRegionalInventories method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, regionalinventory.ListRegionalInventoriesRequest): - request = regionalinventory.ListRegionalInventoriesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_regional_inventories] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListRegionalInventoriesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def insert_regional_inventory(self, - request: Optional[Union[regionalinventory.InsertRegionalInventoryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> regionalinventory.RegionalInventory: - r"""Inserts a ``RegionalInventory`` to a given product in your - merchant account. - - Replaces the full ``RegionalInventory`` resource if an entry - with the same - [``region``][google.shopping.merchant.inventories.v1beta.RegionalInventory.region] - already exists for the product. - - It might take up to 30 minutes for the new or updated - ``RegionalInventory`` resource to appear in products. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_inventories_v1beta - - def sample_insert_regional_inventory(): - # Create a client - client = merchant_inventories_v1beta.RegionalInventoryServiceClient() - - # Initialize request argument(s) - regional_inventory = merchant_inventories_v1beta.RegionalInventory() - regional_inventory.region = "region_value" - - request = merchant_inventories_v1beta.InsertRegionalInventoryRequest( - parent="parent_value", - regional_inventory=regional_inventory, - ) - - # Make the request - response = client.insert_regional_inventory(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_inventories_v1beta.types.InsertRegionalInventoryRequest, dict]): - The request object. Request message for the ``InsertRegionalInventory`` - 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: - google.shopping.merchant_inventories_v1beta.types.RegionalInventory: - Regional inventory information for the product. Represents specific - information like price and availability for a given - product in a specific - [region][google.shopping.merchant.inventories.v1beta.RegionalInventory.region]. - For a list of all accepted attribute values, see the - [regional product inventory data - specification](\ https://support.google.com/merchants/answer/9698880). - - """ - # Create or coerce a protobuf request object. - # - 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, regionalinventory.InsertRegionalInventoryRequest): - request = regionalinventory.InsertRegionalInventoryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.insert_regional_inventory] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_regional_inventory(self, - request: Optional[Union[regionalinventory.DeleteRegionalInventoryRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes the specified ``RegionalInventory`` resource from the - given product in your merchant account. It might take up to an - hour for the ``RegionalInventory`` to be deleted from the - specific product. Once you have received a successful delete - response, wait for that period before attempting a delete again. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.shopping import merchant_inventories_v1beta - - def sample_delete_regional_inventory(): - # Create a client - client = merchant_inventories_v1beta.RegionalInventoryServiceClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.DeleteRegionalInventoryRequest( - name="name_value", - ) - - # Make the request - client.delete_regional_inventory(request=request) - - Args: - request (Union[google.shopping.merchant_inventories_v1beta.types.DeleteRegionalInventoryRequest, dict]): - The request object. Request message for the ``DeleteRegionalInventory`` - method. - name (str): - Required. The name of the ``RegionalInventory`` resource - to delete. Format: - ``accounts/{account}/products/{product}/regionalInventories/{region}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, regionalinventory.DeleteRegionalInventoryRequest): - request = regionalinventory.DeleteRegionalInventoryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_regional_inventory] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def __enter__(self) -> "RegionalInventoryServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER - DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - -__all__ = ( - "RegionalInventoryServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/pagers.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/pagers.py deleted file mode 100644 index ba0ad8732af1..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/pagers.py +++ /dev/null @@ -1,166 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from 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] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore - -from google.shopping.merchant_inventories_v1beta.types import regionalinventory - - -class ListRegionalInventoriesPager: - """A pager for iterating through ``list_regional_inventories`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``regional_inventories`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListRegionalInventories`` requests and continue to iterate - through the ``regional_inventories`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesResponse` - 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[..., regionalinventory.ListRegionalInventoriesResponse], - request: regionalinventory.ListRegionalInventoriesRequest, - response: regionalinventory.ListRegionalInventoriesResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesRequest): - The initial request object. - response (google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = regionalinventory.ListRegionalInventoriesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[regionalinventory.ListRegionalInventoriesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[regionalinventory.RegionalInventory]: - for page in self.pages: - yield from page.regional_inventories - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListRegionalInventoriesAsyncPager: - """A pager for iterating through ``list_regional_inventories`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``regional_inventories`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListRegionalInventories`` requests and continue to iterate - through the ``regional_inventories`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesResponse` - 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[regionalinventory.ListRegionalInventoriesResponse]], - request: regionalinventory.ListRegionalInventoriesRequest, - response: regionalinventory.ListRegionalInventoriesResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesRequest): - The initial request object. - response (google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = regionalinventory.ListRegionalInventoriesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[regionalinventory.ListRegionalInventoriesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[regionalinventory.RegionalInventory]: - async def async_generator(): - async for page in self.pages: - for response in page.regional_inventories: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/README.rst deleted file mode 100644 index 0b66f48dbd0c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`RegionalInventoryServiceTransport` is the ABC for all transports. -- public child `RegionalInventoryServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `RegionalInventoryServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseRegionalInventoryServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `RegionalInventoryServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/base.py deleted file mode 100644 index 8980c90b8cae..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/base.py +++ /dev/null @@ -1,188 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.shopping.merchant_inventories_v1beta 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 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - -from google.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_inventories_v1beta.types import regionalinventory - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER - DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -class RegionalInventoryServiceTransport(abc.ABC): - """Abstract transport class for RegionalInventoryService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/content', - ) - - DEFAULT_HOST: str = 'merchantapi.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: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'merchantapi.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - if not hasattr(self, "_ignore_credentials"): - self._ignore_credentials: bool = False - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_regional_inventories: gapic_v1.method.wrap_method( - self.list_regional_inventories, - default_timeout=None, - client_info=client_info, - ), - self.insert_regional_inventory: gapic_v1.method.wrap_method( - self.insert_regional_inventory, - default_timeout=None, - client_info=client_info, - ), - self.delete_regional_inventory: gapic_v1.method.wrap_method( - self.delete_regional_inventory, - 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! - """ - raise NotImplementedError() - - @property - def list_regional_inventories(self) -> Callable[ - [regionalinventory.ListRegionalInventoriesRequest], - Union[ - regionalinventory.ListRegionalInventoriesResponse, - Awaitable[regionalinventory.ListRegionalInventoriesResponse] - ]]: - raise NotImplementedError() - - @property - def insert_regional_inventory(self) -> Callable[ - [regionalinventory.InsertRegionalInventoryRequest], - Union[ - regionalinventory.RegionalInventory, - Awaitable[regionalinventory.RegionalInventory] - ]]: - raise NotImplementedError() - - @property - def delete_regional_inventory(self) -> Callable[ - [regionalinventory.DeleteRegionalInventoryRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'RegionalInventoryServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc.py deleted file mode 100644 index ed62b0394def..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc.py +++ /dev/null @@ -1,419 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import json -import logging as std_logging -import pickle -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 - -from google.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_inventories_v1beta.types import regionalinventory -from .base import RegionalInventoryServiceTransport, 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 - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER - def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "rpcName": str(client_call_details.method), - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - response = continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = response.result() - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response for {client_call_details.method}.", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class RegionalInventoryServiceGrpcTransport(RegionalInventoryServiceTransport): - """gRPC backend transport for RegionalInventoryService. - - Service to manage regional inventory for products. There is also - separate ``regions`` resource and API to manage regions definitions. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'merchantapi.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: - host (Optional[str]): - The hostname to connect to (default: 'merchantapi.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if a ``channel`` instance is provided. - channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, grpc.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) - - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'merchantapi.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. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_regional_inventories(self) -> Callable[ - [regionalinventory.ListRegionalInventoriesRequest], - regionalinventory.ListRegionalInventoriesResponse]: - r"""Return a callable for the list regional inventories method over gRPC. - - Lists the ``RegionalInventory`` resources for the given product - in your merchant account. The response might contain fewer items - than specified by ``pageSize``. If ``pageToken`` was returned in - previous request, it can be used to obtain additional results. - - ``RegionalInventory`` resources are listed per product for a - given account. - - Returns: - Callable[[~.ListRegionalInventoriesRequest], - ~.ListRegionalInventoriesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_regional_inventories' not in self._stubs: - self._stubs['list_regional_inventories'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/ListRegionalInventories', - request_serializer=regionalinventory.ListRegionalInventoriesRequest.serialize, - response_deserializer=regionalinventory.ListRegionalInventoriesResponse.deserialize, - ) - return self._stubs['list_regional_inventories'] - - @property - def insert_regional_inventory(self) -> Callable[ - [regionalinventory.InsertRegionalInventoryRequest], - regionalinventory.RegionalInventory]: - r"""Return a callable for the insert regional inventory method over gRPC. - - Inserts a ``RegionalInventory`` to a given product in your - merchant account. - - Replaces the full ``RegionalInventory`` resource if an entry - with the same - [``region``][google.shopping.merchant.inventories.v1beta.RegionalInventory.region] - already exists for the product. - - It might take up to 30 minutes for the new or updated - ``RegionalInventory`` resource to appear in products. - - Returns: - Callable[[~.InsertRegionalInventoryRequest], - ~.RegionalInventory]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'insert_regional_inventory' not in self._stubs: - self._stubs['insert_regional_inventory'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/InsertRegionalInventory', - request_serializer=regionalinventory.InsertRegionalInventoryRequest.serialize, - response_deserializer=regionalinventory.RegionalInventory.deserialize, - ) - return self._stubs['insert_regional_inventory'] - - @property - def delete_regional_inventory(self) -> Callable[ - [regionalinventory.DeleteRegionalInventoryRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete regional inventory method over gRPC. - - Deletes the specified ``RegionalInventory`` resource from the - given product in your merchant account. It might take up to an - hour for the ``RegionalInventory`` to be deleted from the - specific product. Once you have received a successful delete - response, wait for that period before attempting a delete again. - - Returns: - Callable[[~.DeleteRegionalInventoryRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_regional_inventory' not in self._stubs: - self._stubs['delete_regional_inventory'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/DeleteRegionalInventory', - request_serializer=regionalinventory.DeleteRegionalInventoryRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_regional_inventory'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'RegionalInventoryServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc_asyncio.py deleted file mode 100644 index e444d0268208..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,450 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import inspect -import json -import pickle -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 retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.protobuf.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.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_inventories_v1beta.types import regionalinventory -from .base import RegionalInventoryServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import RegionalInventoryServiceGrpcTransport - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER - async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "rpcName": str(client_call_details.method), - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - response = await continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = await response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = await response - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response to rpc {client_call_details.method}.", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class RegionalInventoryServiceGrpcAsyncIOTransport(RegionalInventoryServiceTransport): - """gRPC AsyncIO backend transport for RegionalInventoryService. - - Service to manage regional inventory for products. There is also - separate ``regions`` resource and API to manage regions definitions. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'merchantapi.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. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'merchantapi.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: - host (Optional[str]): - The hostname to connect to (default: 'merchantapi.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, aio.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientAIOInterceptor() - self._grpc_channel._unary_unary_interceptors.append(self._interceptor) - self._logged_channel = self._grpc_channel - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_regional_inventories(self) -> Callable[ - [regionalinventory.ListRegionalInventoriesRequest], - Awaitable[regionalinventory.ListRegionalInventoriesResponse]]: - r"""Return a callable for the list regional inventories method over gRPC. - - Lists the ``RegionalInventory`` resources for the given product - in your merchant account. The response might contain fewer items - than specified by ``pageSize``. If ``pageToken`` was returned in - previous request, it can be used to obtain additional results. - - ``RegionalInventory`` resources are listed per product for a - given account. - - Returns: - Callable[[~.ListRegionalInventoriesRequest], - Awaitable[~.ListRegionalInventoriesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_regional_inventories' not in self._stubs: - self._stubs['list_regional_inventories'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/ListRegionalInventories', - request_serializer=regionalinventory.ListRegionalInventoriesRequest.serialize, - response_deserializer=regionalinventory.ListRegionalInventoriesResponse.deserialize, - ) - return self._stubs['list_regional_inventories'] - - @property - def insert_regional_inventory(self) -> Callable[ - [regionalinventory.InsertRegionalInventoryRequest], - Awaitable[regionalinventory.RegionalInventory]]: - r"""Return a callable for the insert regional inventory method over gRPC. - - Inserts a ``RegionalInventory`` to a given product in your - merchant account. - - Replaces the full ``RegionalInventory`` resource if an entry - with the same - [``region``][google.shopping.merchant.inventories.v1beta.RegionalInventory.region] - already exists for the product. - - It might take up to 30 minutes for the new or updated - ``RegionalInventory`` resource to appear in products. - - Returns: - Callable[[~.InsertRegionalInventoryRequest], - Awaitable[~.RegionalInventory]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'insert_regional_inventory' not in self._stubs: - self._stubs['insert_regional_inventory'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/InsertRegionalInventory', - request_serializer=regionalinventory.InsertRegionalInventoryRequest.serialize, - response_deserializer=regionalinventory.RegionalInventory.deserialize, - ) - return self._stubs['insert_regional_inventory'] - - @property - def delete_regional_inventory(self) -> Callable[ - [regionalinventory.DeleteRegionalInventoryRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete regional inventory method over gRPC. - - Deletes the specified ``RegionalInventory`` resource from the - given product in your merchant account. It might take up to an - hour for the ``RegionalInventory`` to be deleted from the - specific product. Once you have received a successful delete - response, wait for that period before attempting a delete again. - - Returns: - Callable[[~.DeleteRegionalInventoryRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_regional_inventory' not in self._stubs: - self._stubs['delete_regional_inventory'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1beta.RegionalInventoryService/DeleteRegionalInventory', - request_serializer=regionalinventory.DeleteRegionalInventoryRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_regional_inventory'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.list_regional_inventories: self._wrap_method( - self.list_regional_inventories, - default_timeout=None, - client_info=client_info, - ), - self.insert_regional_inventory: self._wrap_method( - self.insert_regional_inventory, - default_timeout=None, - client_info=client_info, - ), - self.delete_regional_inventory: self._wrap_method( - self.delete_regional_inventory, - default_timeout=None, - client_info=client_info, - ), - } - - def _wrap_method(self, func, *args, **kwargs): - if self._wrap_with_kind: # pragma: NO COVER - kwargs["kind"] = self.kind - return gapic_v1.method_async.wrap_method(func, *args, **kwargs) - - def close(self): - return self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - -__all__ = ( - 'RegionalInventoryServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest.py deleted file mode 100644 index 3991d4beb736..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest.py +++ /dev/null @@ -1,644 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import 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 warnings - - -from google.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_inventories_v1beta.types import regionalinventory - - -from .rest_base import _BaseRegionalInventoryServiceRestTransport -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = logging.getLogger(__name__) - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=f"requests@{requests_version}", -) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER - DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -class RegionalInventoryServiceRestInterceptor: - """Interceptor for RegionalInventoryService. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the RegionalInventoryServiceRestTransport. - - .. code-block:: python - class MyCustomRegionalInventoryServiceInterceptor(RegionalInventoryServiceRestInterceptor): - def pre_delete_regional_inventory(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_insert_regional_inventory(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_insert_regional_inventory(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_regional_inventories(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_regional_inventories(self, response): - logging.log(f"Received response: {response}") - return response - - transport = RegionalInventoryServiceRestTransport(interceptor=MyCustomRegionalInventoryServiceInterceptor()) - client = RegionalInventoryServiceClient(transport=transport) - - - """ - def pre_delete_regional_inventory(self, request: regionalinventory.DeleteRegionalInventoryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regionalinventory.DeleteRegionalInventoryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_regional_inventory - - Override in a subclass to manipulate the request or metadata - before they are sent to the RegionalInventoryService server. - """ - return request, metadata - - def pre_insert_regional_inventory(self, request: regionalinventory.InsertRegionalInventoryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regionalinventory.InsertRegionalInventoryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for insert_regional_inventory - - Override in a subclass to manipulate the request or metadata - before they are sent to the RegionalInventoryService server. - """ - return request, metadata - - def post_insert_regional_inventory(self, response: regionalinventory.RegionalInventory) -> regionalinventory.RegionalInventory: - """Post-rpc interceptor for insert_regional_inventory - - DEPRECATED. Please use the `post_insert_regional_inventory_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the RegionalInventoryService server but before - it is returned to user code. This `post_insert_regional_inventory` interceptor runs - before the `post_insert_regional_inventory_with_metadata` interceptor. - """ - return response - - def post_insert_regional_inventory_with_metadata(self, response: regionalinventory.RegionalInventory, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regionalinventory.RegionalInventory, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for insert_regional_inventory - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the RegionalInventoryService server but before it is returned to user code. - - We recommend only using this `post_insert_regional_inventory_with_metadata` - interceptor in new development instead of the `post_insert_regional_inventory` interceptor. - When both interceptors are used, this `post_insert_regional_inventory_with_metadata` interceptor runs after the - `post_insert_regional_inventory` interceptor. The (possibly modified) response returned by - `post_insert_regional_inventory` will be passed to - `post_insert_regional_inventory_with_metadata`. - """ - return response, metadata - - def pre_list_regional_inventories(self, request: regionalinventory.ListRegionalInventoriesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regionalinventory.ListRegionalInventoriesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_regional_inventories - - Override in a subclass to manipulate the request or metadata - before they are sent to the RegionalInventoryService server. - """ - return request, metadata - - def post_list_regional_inventories(self, response: regionalinventory.ListRegionalInventoriesResponse) -> regionalinventory.ListRegionalInventoriesResponse: - """Post-rpc interceptor for list_regional_inventories - - DEPRECATED. Please use the `post_list_regional_inventories_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the RegionalInventoryService server but before - it is returned to user code. This `post_list_regional_inventories` interceptor runs - before the `post_list_regional_inventories_with_metadata` interceptor. - """ - return response - - def post_list_regional_inventories_with_metadata(self, response: regionalinventory.ListRegionalInventoriesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regionalinventory.ListRegionalInventoriesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_regional_inventories - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the RegionalInventoryService server but before it is returned to user code. - - We recommend only using this `post_list_regional_inventories_with_metadata` - interceptor in new development instead of the `post_list_regional_inventories` interceptor. - When both interceptors are used, this `post_list_regional_inventories_with_metadata` interceptor runs after the - `post_list_regional_inventories` interceptor. The (possibly modified) response returned by - `post_list_regional_inventories` will be passed to - `post_list_regional_inventories_with_metadata`. - """ - return response, metadata - - -@dataclasses.dataclass -class RegionalInventoryServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: RegionalInventoryServiceRestInterceptor - - -class RegionalInventoryServiceRestTransport(_BaseRegionalInventoryServiceRestTransport): - """REST backend synchronous transport for RegionalInventoryService. - - Service to manage regional inventory for products. There is also - separate ``regions`` resource and API to manage regions definitions. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'merchantapi.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[RegionalInventoryServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'merchantapi.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - url_scheme=url_scheme, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or RegionalInventoryServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _DeleteRegionalInventory(_BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory, RegionalInventoryServiceRestStub): - def __hash__(self): - return hash("RegionalInventoryServiceRestTransport.DeleteRegionalInventory") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: regionalinventory.DeleteRegionalInventoryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): - r"""Call the delete regional inventory method over HTTP. - - Args: - request (~.regionalinventory.DeleteRegionalInventoryRequest): - The request object. Request message for the ``DeleteRegionalInventory`` - 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 = _BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._get_http_options() - - request, metadata = self._interceptor.pre_delete_regional_inventory(request, metadata) - transcoded_request = _BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient.DeleteRegionalInventory", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "rpcName": "DeleteRegionalInventory", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = RegionalInventoryServiceRestTransport._DeleteRegionalInventory._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 _InsertRegionalInventory(_BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory, RegionalInventoryServiceRestStub): - def __hash__(self): - return hash("RegionalInventoryServiceRestTransport.InsertRegionalInventory") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: regionalinventory.InsertRegionalInventoryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> regionalinventory.RegionalInventory: - r"""Call the insert regional inventory method over HTTP. - - Args: - request (~.regionalinventory.InsertRegionalInventoryRequest): - The request object. Request message for the ``InsertRegionalInventory`` - 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: - ~.regionalinventory.RegionalInventory: - Regional inventory information for the product. - Represents specific information like price and - availability for a given product in a specific - [``region``][google.shopping.merchant.inventories.v1beta.RegionalInventory.region]. - For a list of all accepted attribute values, see the - `regional product inventory data - specification `__. - - """ - - http_options = _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_http_options() - - request, metadata = self._interceptor.pre_insert_regional_inventory(request, metadata) - transcoded_request = _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_transcoded_request(http_options, request) - - body = _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient.InsertRegionalInventory", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "rpcName": "InsertRegionalInventory", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = RegionalInventoryServiceRestTransport._InsertRegionalInventory._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = regionalinventory.RegionalInventory() - pb_resp = regionalinventory.RegionalInventory.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_insert_regional_inventory(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_insert_regional_inventory_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = regionalinventory.RegionalInventory.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient.insert_regional_inventory", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "rpcName": "InsertRegionalInventory", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListRegionalInventories(_BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories, RegionalInventoryServiceRestStub): - def __hash__(self): - return hash("RegionalInventoryServiceRestTransport.ListRegionalInventories") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: regionalinventory.ListRegionalInventoriesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> regionalinventory.ListRegionalInventoriesResponse: - r"""Call the list regional inventories method over HTTP. - - Args: - request (~.regionalinventory.ListRegionalInventoriesRequest): - The request object. Request message for the ``ListRegionalInventories`` - 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: - ~.regionalinventory.ListRegionalInventoriesResponse: - Response message for the ``ListRegionalInventories`` - method. - - """ - - http_options = _BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._get_http_options() - - request, metadata = self._interceptor.pre_list_regional_inventories(request, metadata) - transcoded_request = _BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient.ListRegionalInventories", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "rpcName": "ListRegionalInventories", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = RegionalInventoryServiceRestTransport._ListRegionalInventories._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = regionalinventory.ListRegionalInventoriesResponse() - pb_resp = regionalinventory.ListRegionalInventoriesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_regional_inventories(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_regional_inventories_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = regionalinventory.ListRegionalInventoriesResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.shopping.merchant.inventories_v1beta.RegionalInventoryServiceClient.list_regional_inventories", - extra = { - "serviceName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "rpcName": "ListRegionalInventories", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def delete_regional_inventory(self) -> Callable[ - [regionalinventory.DeleteRegionalInventoryRequest], - 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._DeleteRegionalInventory(self._session, self._host, self._interceptor) # type: ignore - - @property - def insert_regional_inventory(self) -> Callable[ - [regionalinventory.InsertRegionalInventoryRequest], - regionalinventory.RegionalInventory]: - # 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._InsertRegionalInventory(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_regional_inventories(self) -> Callable[ - [regionalinventory.ListRegionalInventoriesRequest], - regionalinventory.ListRegionalInventoriesResponse]: - # 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._ListRegionalInventories(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'RegionalInventoryServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest_base.py deleted file mode 100644 index 5da5c1f7431f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/rest_base.py +++ /dev/null @@ -1,213 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import json # type: ignore -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from .base import RegionalInventoryServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_inventories_v1beta.types import regionalinventory - - -class _BaseRegionalInventoryServiceRestTransport(RegionalInventoryServiceTransport): - """Base REST backend transport for RegionalInventoryService. - - Note: This class is not meant to be used directly. Use its sync and - async sub-classes instead. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'merchantapi.googleapis.com', - credentials: Optional[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - Args: - host (Optional[str]): - The hostname to connect to (default: 'merchantapi.googleapis.com'). - credentials (Optional[Any]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - - class _BaseDeleteRegionalInventory: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/inventories/v1beta/{name=accounts/*/products/*/regionalInventories/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = regionalinventory.DeleteRegionalInventoryRequest.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(_BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseInsertRegionalInventory: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/inventories/v1beta/{parent=accounts/*/products/*}/regionalInventories:insert', - 'body': 'regional_inventory', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = regionalinventory.InsertRegionalInventoryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListRegionalInventories: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/inventories/v1beta/{parent=accounts/*/products/*}/regionalInventories', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = regionalinventory.ListRegionalInventoriesRequest.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(_BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseRegionalInventoryServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/localinventory.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/localinventory.py deleted file mode 100644 index 9183d2bf4942..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/localinventory.py +++ /dev/null @@ -1,281 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.shopping.type.types import types -from google.type import interval_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.shopping.merchant.inventories.v1beta', - manifest={ - 'LocalInventory', - 'ListLocalInventoriesRequest', - 'ListLocalInventoriesResponse', - 'InsertLocalInventoryRequest', - 'DeleteLocalInventoryRequest', - }, -) - - -class LocalInventory(proto.Message): - r"""Local inventory information for the product. Represents in-store - information for a specific product at the store specified by - [``storeCode``][google.shopping.merchant.inventories.v1beta.LocalInventory.store_code]. - For a list of all accepted attribute values, see the `local product - inventory data - specification `__. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Output only. The name of the ``LocalInventory`` resource. - Format: - ``accounts/{account}/products/{product}/localInventories/{store_code}`` - account (int): - Output only. The account that owns the - product. This field will be ignored if set by - the client. - store_code (str): - Required. Immutable. Store code (the store ID from your - Business Profile) of the physical store the product is sold - in. See the `Local product inventory data - specification `__ - for more information. - price (google.shopping.type.types.Price): - Price of the product at this store. - sale_price (google.shopping.type.types.Price): - Sale price of the product at this store. Mandatory if - [``salePriceEffectiveDate``][google.shopping.merchant.inventories.v1beta.LocalInventory.sale_price_effective_date] - is defined. - sale_price_effective_date (google.type.interval_pb2.Interval): - The ``TimePeriod`` of the sale at this store. - availability (str): - Availability of the product at this store. For accepted - attribute values, see the `local product inventory data - specification `__ - - This field is a member of `oneof`_ ``_availability``. - quantity (int): - Quantity of the product available at this - store. Must be greater than or equal to zero. - - This field is a member of `oneof`_ ``_quantity``. - pickup_method (str): - Supported pickup method for this product. Unless the value - is ``"not supported"``, this field must be submitted - together with ``pickupSla``. For accepted attribute values, - see the `local product inventory data - specification `__ - - This field is a member of `oneof`_ ``_pickup_method``. - pickup_sla (str): - Relative time period from the order date for an order for - this product, from this store, to be ready for pickup. Must - be submitted with ``pickupMethod``. For accepted attribute - values, see the `local product inventory data - specification `__ - - This field is a member of `oneof`_ ``_pickup_sla``. - instore_product_location (str): - Location of the product inside the store. - Maximum length is 20 bytes. - - This field is a member of `oneof`_ ``_instore_product_location``. - custom_attributes (MutableSequence[google.shopping.type.types.CustomAttribute]): - A list of custom (merchant-provided) attributes. You can - also use ``CustomAttribute`` to submit any attribute of the - data specification in its generic form. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - account: int = proto.Field( - proto.INT64, - number=2, - ) - store_code: str = proto.Field( - proto.STRING, - number=3, - ) - price: types.Price = proto.Field( - proto.MESSAGE, - number=4, - message=types.Price, - ) - sale_price: types.Price = proto.Field( - proto.MESSAGE, - number=5, - message=types.Price, - ) - sale_price_effective_date: interval_pb2.Interval = proto.Field( - proto.MESSAGE, - number=6, - message=interval_pb2.Interval, - ) - availability: str = proto.Field( - proto.STRING, - number=7, - optional=True, - ) - quantity: int = proto.Field( - proto.INT64, - number=8, - optional=True, - ) - pickup_method: str = proto.Field( - proto.STRING, - number=9, - optional=True, - ) - pickup_sla: str = proto.Field( - proto.STRING, - number=10, - optional=True, - ) - instore_product_location: str = proto.Field( - proto.STRING, - number=11, - optional=True, - ) - custom_attributes: MutableSequence[types.CustomAttribute] = proto.RepeatedField( - proto.MESSAGE, - number=12, - message=types.CustomAttribute, - ) - - -class ListLocalInventoriesRequest(proto.Message): - r"""Request message for the ``ListLocalInventories`` method. - - Attributes: - parent (str): - Required. The ``name`` of the parent product to list local - inventories for. Format: - ``accounts/{account}/products/{product}`` - page_size (int): - The maximum number of ``LocalInventory`` resources for the - given product to return. The service returns fewer than this - value if the number of inventories for the given product is - less that than the ``pageSize``. The default value is 25000. - The maximum value is 25000; If a value higher than the - maximum is specified, then the ``pageSize`` will default to - the maximum - page_token (str): - A page token, received from a previous - ``ListLocalInventories`` call. Provide the page token to - retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListLocalInventories`` must match the call that provided - the page token. The token returned as - [nextPageToken][google.shopping.merchant.inventories.v1beta.ListLocalInventoriesResponse.next_page_token] - in the response to the previous request. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListLocalInventoriesResponse(proto.Message): - r"""Response message for the ``ListLocalInventories`` method. - - Attributes: - local_inventories (MutableSequence[google.shopping.merchant_inventories_v1beta.types.LocalInventory]): - The ``LocalInventory`` resources for the given product from - the specified account. - next_page_token (str): - A token, which can be sent as ``pageToken`` to retrieve the - next page. If this field is omitted, there are no subsequent - pages. - """ - - @property - def raw_page(self): - return self - - local_inventories: MutableSequence['LocalInventory'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='LocalInventory', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class InsertLocalInventoryRequest(proto.Message): - r"""Request message for the ``InsertLocalInventory`` method. - - Attributes: - parent (str): - Required. The account and product where this inventory will - be inserted. Format: - ``accounts/{account}/products/{product}`` - local_inventory (google.shopping.merchant_inventories_v1beta.types.LocalInventory): - Required. Local inventory information of the product. If the - product already has a ``LocalInventory`` resource for the - same ``storeCode``, full replacement of the - ``LocalInventory`` resource is performed. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - local_inventory: 'LocalInventory' = proto.Field( - proto.MESSAGE, - number=2, - message='LocalInventory', - ) - - -class DeleteLocalInventoryRequest(proto.Message): - r"""Request message for the ``DeleteLocalInventory`` method. - - Attributes: - name (str): - Required. The name of the local inventory for the given - product to delete. Format: - ``accounts/{account}/products/{product}/localInventories/{store_code}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/regionalinventory.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/regionalinventory.py deleted file mode 100644 index fe06b511d070..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/regionalinventory.py +++ /dev/null @@ -1,236 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.shopping.type.types import types -from google.type import interval_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.shopping.merchant.inventories.v1beta', - manifest={ - 'RegionalInventory', - 'ListRegionalInventoriesRequest', - 'ListRegionalInventoriesResponse', - 'InsertRegionalInventoryRequest', - 'DeleteRegionalInventoryRequest', - }, -) - - -class RegionalInventory(proto.Message): - r"""Regional inventory information for the product. Represents specific - information like price and availability for a given product in a - specific - [``region``][google.shopping.merchant.inventories.v1beta.RegionalInventory.region]. - For a list of all accepted attribute values, see the `regional - product inventory data - specification `__. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Output only. The name of the ``RegionalInventory`` resource. - Format: - ``{regional_inventory.name=accounts/{account}/products/{product}/regionalInventories/{region}`` - account (int): - Output only. The account that owns the - product. This field will be ignored if set by - the client. - region (str): - Required. Immutable. ID of the region for this - ``RegionalInventory`` resource. See the `Regional - availability and - pricing `__ - for more details. - price (google.shopping.type.types.Price): - Price of the product in this region. - sale_price (google.shopping.type.types.Price): - Sale price of the product in this region. Mandatory if - [``salePriceEffectiveDate``][google.shopping.merchant.inventories.v1beta.RegionalInventory.sale_price_effective_date] - is defined. - sale_price_effective_date (google.type.interval_pb2.Interval): - The ``TimePeriod`` of the sale price in this region. - availability (str): - Availability of the product in this region. For accepted - attribute values, see the `regional product inventory data - specification `__ - - This field is a member of `oneof`_ ``_availability``. - custom_attributes (MutableSequence[google.shopping.type.types.CustomAttribute]): - A list of custom (merchant-provided) attributes. You can - also use ``CustomAttribute`` to submit any attribute of the - data specification in its generic form. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - account: int = proto.Field( - proto.INT64, - number=2, - ) - region: str = proto.Field( - proto.STRING, - number=3, - ) - price: types.Price = proto.Field( - proto.MESSAGE, - number=4, - message=types.Price, - ) - sale_price: types.Price = proto.Field( - proto.MESSAGE, - number=5, - message=types.Price, - ) - sale_price_effective_date: interval_pb2.Interval = proto.Field( - proto.MESSAGE, - number=6, - message=interval_pb2.Interval, - ) - availability: str = proto.Field( - proto.STRING, - number=7, - optional=True, - ) - custom_attributes: MutableSequence[types.CustomAttribute] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message=types.CustomAttribute, - ) - - -class ListRegionalInventoriesRequest(proto.Message): - r"""Request message for the ``ListRegionalInventories`` method. - - Attributes: - parent (str): - Required. The ``name`` of the parent product to list - ``RegionalInventory`` resources for. Format: - ``accounts/{account}/products/{product}`` - page_size (int): - The maximum number of ``RegionalInventory`` resources for - the given product to return. The service returns fewer than - this value if the number of inventories for the given - product is less that than the ``pageSize``. The default - value is 25000. The maximum value is 100000; If a value - higher than the maximum is specified, then the ``pageSize`` - will default to the maximum. - page_token (str): - A page token, received from a previous - ``ListRegionalInventories`` call. Provide the page token to - retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListRegionalInventories`` must match the call that - provided the page token. The token returned as - [nextPageToken][google.shopping.merchant.inventories.v1beta.ListRegionalInventoriesResponse.next_page_token] - in the response to the previous request. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListRegionalInventoriesResponse(proto.Message): - r"""Response message for the ``ListRegionalInventories`` method. - - Attributes: - regional_inventories (MutableSequence[google.shopping.merchant_inventories_v1beta.types.RegionalInventory]): - The ``RegionalInventory`` resources for the given product - from the specified account. - next_page_token (str): - A token, which can be sent as ``pageToken`` to retrieve the - next page. If this field is omitted, there are no subsequent - pages. - """ - - @property - def raw_page(self): - return self - - regional_inventories: MutableSequence['RegionalInventory'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='RegionalInventory', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class InsertRegionalInventoryRequest(proto.Message): - r"""Request message for the ``InsertRegionalInventory`` method. - - Attributes: - parent (str): - Required. The account and product where this inventory will - be inserted. Format: - ``accounts/{account}/products/{product}`` - regional_inventory (google.shopping.merchant_inventories_v1beta.types.RegionalInventory): - Required. Regional inventory information to add to the - product. If the product already has a ``RegionalInventory`` - resource for the same ``region``, full replacement of the - ``RegionalInventory`` resource is performed. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - regional_inventory: 'RegionalInventory' = proto.Field( - proto.MESSAGE, - number=2, - message='RegionalInventory', - ) - - -class DeleteRegionalInventoryRequest(proto.Message): - r"""Request message for the ``DeleteRegionalInventory`` method. - - Attributes: - name (str): - Required. The name of the ``RegionalInventory`` resource to - delete. Format: - ``accounts/{account}/products/{product}/regionalInventories/{region}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/mypy.ini b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/noxfile.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/noxfile.py deleted file mode 100644 index 084984b159e7..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/noxfile.py +++ /dev/null @@ -1,591 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import re -import shutil - -from typing import Dict, List -import warnings - -import nox - -BLACK_VERSION = "black[jupyter]==23.7.0" -ISORT_VERSION = "isort==5.11.0" - -LINT_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -DEFAULT_PYTHON_VERSION = ALL_PYTHON[-1] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = "google-shopping-merchant-inventories" - -UNIT_TEST_STANDARD_DEPENDENCIES = [ - "mock", - "asyncmock", - "pytest", - "pytest-cov", - "pytest-asyncio", -] -UNIT_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] -UNIT_TEST_LOCAL_DEPENDENCIES: List[str] = [] -UNIT_TEST_DEPENDENCIES: List[str] = [] -UNIT_TEST_EXTRAS: List[str] = [] -UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} - -SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] -SYSTEM_TEST_STANDARD_DEPENDENCIES = [ - "mock", - "pytest", - "google-cloud-testutils", -] -SYSTEM_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] -SYSTEM_TEST_LOCAL_DEPENDENCIES: List[str] = [] -SYSTEM_TEST_DEPENDENCIES: List[str] = [] -SYSTEM_TEST_EXTRAS: List[str] = [] -SYSTEM_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} - -nox.options.sessions = [ - "unit", - "system", - "cover", - "lint", - "lint_setup_py", - "blacken", - "docs", -] - -# Error if a python version is missing -nox.options.error_on_missing_interpreters = True - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - "mypy", - "types-requests", - "types-protobuf", - ) - session.install(".") - session.run( - "mypy", - "-p", - "google", - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install("google-cloud-testutils") - session.install(".") - - session.run( - "lower-bound-checker", - "update", - "--package-name", - PACKAGE_NAME, - "--constraints-file", - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install("google-cloud-testutils") - session.install(".") - - session.run( - "lower-bound-checker", - "check", - "--package-name", - PACKAGE_NAME, - "--constraints-file", - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *LINT_PATHS, - ) - - session.run("flake8", "google", "tests") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *LINT_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def format(session): - """ - Run isort to sort imports. Then run black - to format code to uniform standard. - """ - session.install(BLACK_VERSION, ISORT_VERSION) - # Use the --fss option to sort imports using strict alphabetical order. - # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections - session.run( - "isort", - "--fss", - *LINT_PATHS, - ) - session.run( - "black", - *LINT_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("setuptools", "docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") - - -def install_unittest_dependencies(session, *constraints): - standard_deps = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_DEPENDENCIES - session.install(*standard_deps, *constraints) - - if UNIT_TEST_EXTERNAL_DEPENDENCIES: - warnings.warn( - "'unit_test_external_dependencies' is deprecated. Instead, please " - "use 'unit_test_dependencies' or 'unit_test_local_dependencies'.", - DeprecationWarning, - ) - session.install(*UNIT_TEST_EXTERNAL_DEPENDENCIES, *constraints) - - if UNIT_TEST_LOCAL_DEPENDENCIES: - session.install(*UNIT_TEST_LOCAL_DEPENDENCIES, *constraints) - - if UNIT_TEST_EXTRAS_BY_PYTHON: - extras = UNIT_TEST_EXTRAS_BY_PYTHON.get(session.python, []) - elif UNIT_TEST_EXTRAS: - extras = UNIT_TEST_EXTRAS - else: - extras = [] - - if extras: - session.install("-e", f".[{','.join(extras)}]", *constraints) - else: - session.install("-e", ".", *constraints) - - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - ["python", "upb", "cpp"], -) -def unit(session, protobuf_implementation): - # Install all test dependencies, then install this package in-place. - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): - session.skip("cpp implementation is not supported in python 3.11+") - - constraints_path = str( - CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" - ) - install_unittest_dependencies(session, "-c", constraints_path) - - # TODO(https://github.com/googleapis/synthtool/issues/1976): - # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. - # The 'cpp' implementation requires Protobuf<4. - if protobuf_implementation == "cpp": - session.install("protobuf<4") - - # Run py.test against the unit tests. - session.run( - "py.test", - "--quiet", - f"--junitxml=unit_{session.python}_sponge_log.xml", - "--cov=google", - "--cov=tests/unit", - "--cov-append", - "--cov-config=.coveragerc", - "--cov-report=", - "--cov-fail-under=0", - os.path.join("tests", "unit"), - *session.posargs, - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -def install_systemtest_dependencies(session, *constraints): - session.install("--pre", "grpcio") - - session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_EXTERNAL_DEPENDENCIES: - session.install(*SYSTEM_TEST_EXTERNAL_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_LOCAL_DEPENDENCIES: - session.install("-e", *SYSTEM_TEST_LOCAL_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_DEPENDENCIES: - session.install("-e", *SYSTEM_TEST_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_EXTRAS_BY_PYTHON: - extras = SYSTEM_TEST_EXTRAS_BY_PYTHON.get(session.python, []) - elif SYSTEM_TEST_EXTRAS: - extras = SYSTEM_TEST_EXTRAS - else: - extras = [] - - if extras: - session.install("-e", f".[{','.join(extras)}]", *constraints) - else: - session.install("-e", ".", *constraints) - - -@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) -def system(session): - """Run the system test suite.""" - constraints_path = str( - CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" - ) - system_test_path = os.path.join("tests", "system.py") - system_test_folder_path = os.path.join("tests", "system") - - # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. - if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": - session.skip("RUN_SYSTEM_TESTS is set to false, skipping") - # Install pyopenssl for mTLS testing. - if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": - session.install("pyopenssl") - - system_test_exists = os.path.exists(system_test_path) - system_test_folder_exists = os.path.exists(system_test_folder_path) - # Sanity check: only run tests if found. - if not system_test_exists and not system_test_folder_exists: - session.skip("System tests were not found") - - install_systemtest_dependencies(session, "-c", constraints_path) - - # Run py.test against the system tests. - if system_test_exists: - session.run( - "py.test", - "--quiet", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_path, - *session.posargs, - ) - if system_test_folder_exists: - session.run( - "py.test", - "--quiet", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_folder_path, - *session.posargs, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python="3.10") -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install( - # We need to pin to specific versions of the `sphinxcontrib-*` packages - # which still support sphinx 4.x. - # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 - # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. - "sphinxcontrib-applehelp==1.0.4", - "sphinxcontrib-devhelp==1.0.2", - "sphinxcontrib-htmlhelp==2.0.1", - "sphinxcontrib-qthelp==1.0.3", - "sphinxcontrib-serializinghtml==1.1.5", - "sphinx==4.5.0", - "alabaster", - "recommonmark", - ) - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python="3.10") -def docfx(session): - """Build the docfx yaml files for this library.""" - - session.install("-e", ".") - session.install( - # We need to pin to specific versions of the `sphinxcontrib-*` packages - # which still support sphinx 4.x. - # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 - # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. - "sphinxcontrib-applehelp==1.0.4", - "sphinxcontrib-devhelp==1.0.2", - "sphinxcontrib-htmlhelp==2.0.1", - "sphinxcontrib-qthelp==1.0.3", - "sphinxcontrib-serializinghtml==1.1.5", - "gcp-sphinx-docfx-yaml", - "alabaster", - "recommonmark", - ) - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-T", # show full traceback on exception - "-N", # no colors - "-D", - ( - "extensions=sphinx.ext.autodoc," - "sphinx.ext.autosummary," - "docfx_yaml.extension," - "sphinx.ext.intersphinx," - "sphinx.ext.coverage," - "sphinx.ext.napoleon," - "sphinx.ext.todo," - "sphinx.ext.viewcode," - "recommonmark" - ), - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -@nox.parametrize( - "protobuf_implementation", - ["python", "upb", "cpp"], -) -def prerelease_deps(session, protobuf_implementation): - """ - Run all tests with pre-release versions of dependencies installed - rather than the standard non pre-release versions. - Pre-release versions can be installed using - `pip install --pre `. - """ - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): - session.skip("cpp implementation is not supported in python 3.11+") - - # Install all dependencies - session.install("-e", ".") - - # Install dependencies for the unit test environment - unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES - session.install(*unit_deps_all) - - # Install dependencies for the system test environment - system_deps_all = ( - SYSTEM_TEST_STANDARD_DEPENDENCIES - + SYSTEM_TEST_EXTERNAL_DEPENDENCIES - + SYSTEM_TEST_EXTRAS - ) - session.install(*system_deps_all) - - # Because we test minimum dependency versions on the minimum Python - # version, the first version we test with in the unit tests sessions has a - # constraints file containing all dependencies and extras. - with open( - CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) - - # Note: If a dependency is added to the `prerel_deps` list, - # the `core_dependencies_from_source` list in the `core_deps_from_source` - # nox session should also be updated. - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - "grpc-google-iam-v1", - "grpcio", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--ignore-installed", dep) - # TODO(https://github.com/grpc/grpc/issues/38965): Add `grpcio-status`` - # to the dictionary below once this bug is fixed. - # TODO(https://github.com/googleapis/google-cloud-python/issues/13643): Add - # `googleapis-common-protos` and `grpc-google-iam-v1` to the dictionary below - # once this bug is fixed. - package_namespaces = { - "google-api-core": "google.api_core", - "google-auth": "google.auth", - "grpcio": "grpc", - "protobuf": "google.protobuf", - "proto-plus": "proto", - } - - version_namespace = package_namespaces.get(dep) - - print(f"Installed {dep}") - if version_namespace: - session.run( - "python", - "-c", - f"import {version_namespace}; print({version_namespace}.__version__)", - ) - - session.run( - "py.test", - "tests/unit", - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -@nox.parametrize( - "protobuf_implementation", - ["python", "upb"], -) -def core_deps_from_source(session, protobuf_implementation): - """Run all tests with core dependencies installed from source - rather than pulling the dependencies from PyPI. - """ - - # Install all dependencies - session.install("-e", ".") - - # Install dependencies for the unit test environment - unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES - session.install(*unit_deps_all) - - # Install dependencies for the system test environment - system_deps_all = ( - SYSTEM_TEST_STANDARD_DEPENDENCIES - + SYSTEM_TEST_EXTERNAL_DEPENDENCIES - + SYSTEM_TEST_EXTRAS - ) - session.install(*system_deps_all) - - # Because we test minimum dependency versions on the minimum Python - # version, the first version we test with in the unit tests sessions has a - # constraints file containing all dependencies and extras. - with open( - CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) - - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and - # `grpcio-status` should be added to the list below so that they are installed from source, - # rather than PyPI. - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2357): `protobuf` should be - # added to the list below so that it is installed from source, rather than PyPI - # Note: If a dependency is added to the `core_dependencies_from_source` list, - # the `prerel_deps` list in the `prerelease_deps` nox session should also be updated. - core_dependencies_from_source = [ - "googleapis-common-protos @ git+https://github.com/googleapis/google-cloud-python#egg=googleapis-common-protos&subdirectory=packages/googleapis-common-protos", - "google-api-core @ git+https://github.com/googleapis/python-api-core.git", - "google-auth @ git+https://github.com/googleapis/google-auth-library-python.git", - "grpc-google-iam-v1 @ git+https://github.com/googleapis/google-cloud-python#egg=grpc-google-iam-v1&subdirectory=packages/grpc-google-iam-v1", - "proto-plus @ git+https://github.com/googleapis/proto-plus-python.git", - ] - - for dep in core_dependencies_from_source: - session.install(dep, "--no-deps", "--ignore-installed") - print(f"Installed {dep}") - - session.run( - "py.test", - "tests/unit", - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_async.py deleted file mode 100644 index b943553049d3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteLocalInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-inventories - - -# [START merchantapi_v1beta_generated_LocalInventoryService_DeleteLocalInventory_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_inventories_v1beta - - -async def sample_delete_local_inventory(): - # Create a client - client = merchant_inventories_v1beta.LocalInventoryServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.DeleteLocalInventoryRequest( - name="name_value", - ) - - # Make the request - await client.delete_local_inventory(request=request) - - -# [END merchantapi_v1beta_generated_LocalInventoryService_DeleteLocalInventory_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_sync.py deleted file mode 100644 index 8c7fd4ce178e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteLocalInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-inventories - - -# [START merchantapi_v1beta_generated_LocalInventoryService_DeleteLocalInventory_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_inventories_v1beta - - -def sample_delete_local_inventory(): - # Create a client - client = merchant_inventories_v1beta.LocalInventoryServiceClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.DeleteLocalInventoryRequest( - name="name_value", - ) - - # Make the request - client.delete_local_inventory(request=request) - - -# [END merchantapi_v1beta_generated_LocalInventoryService_DeleteLocalInventory_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_async.py deleted file mode 100644 index 06103e944a86..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for InsertLocalInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-inventories - - -# [START merchantapi_v1beta_generated_LocalInventoryService_InsertLocalInventory_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_inventories_v1beta - - -async def sample_insert_local_inventory(): - # Create a client - client = merchant_inventories_v1beta.LocalInventoryServiceAsyncClient() - - # Initialize request argument(s) - local_inventory = merchant_inventories_v1beta.LocalInventory() - local_inventory.store_code = "store_code_value" - - request = merchant_inventories_v1beta.InsertLocalInventoryRequest( - parent="parent_value", - local_inventory=local_inventory, - ) - - # Make the request - response = await client.insert_local_inventory(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_LocalInventoryService_InsertLocalInventory_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_sync.py deleted file mode 100644 index 7f36fb1e49d8..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for InsertLocalInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-inventories - - -# [START merchantapi_v1beta_generated_LocalInventoryService_InsertLocalInventory_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_inventories_v1beta - - -def sample_insert_local_inventory(): - # Create a client - client = merchant_inventories_v1beta.LocalInventoryServiceClient() - - # Initialize request argument(s) - local_inventory = merchant_inventories_v1beta.LocalInventory() - local_inventory.store_code = "store_code_value" - - request = merchant_inventories_v1beta.InsertLocalInventoryRequest( - parent="parent_value", - local_inventory=local_inventory, - ) - - # Make the request - response = client.insert_local_inventory(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_LocalInventoryService_InsertLocalInventory_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_async.py deleted file mode 100644 index 28c3b798d98a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-inventories - - -# [START merchantapi_v1beta_generated_LocalInventoryService_ListLocalInventories_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_inventories_v1beta - - -async def sample_list_local_inventories(): - # Create a client - client = merchant_inventories_v1beta.LocalInventoryServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.ListLocalInventoriesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_local_inventories(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_LocalInventoryService_ListLocalInventories_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_sync.py deleted file mode 100644 index 0da9a3949ef0..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListLocalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-inventories - - -# [START merchantapi_v1beta_generated_LocalInventoryService_ListLocalInventories_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_inventories_v1beta - - -def sample_list_local_inventories(): - # Create a client - client = merchant_inventories_v1beta.LocalInventoryServiceClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.ListLocalInventoriesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_local_inventories(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_LocalInventoryService_ListLocalInventories_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_async.py deleted file mode 100644 index a94f70d57db0..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteRegionalInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-inventories - - -# [START merchantapi_v1beta_generated_RegionalInventoryService_DeleteRegionalInventory_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_inventories_v1beta - - -async def sample_delete_regional_inventory(): - # Create a client - client = merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.DeleteRegionalInventoryRequest( - name="name_value", - ) - - # Make the request - await client.delete_regional_inventory(request=request) - - -# [END merchantapi_v1beta_generated_RegionalInventoryService_DeleteRegionalInventory_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_sync.py deleted file mode 100644 index e128acbf9531..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteRegionalInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-inventories - - -# [START merchantapi_v1beta_generated_RegionalInventoryService_DeleteRegionalInventory_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_inventories_v1beta - - -def sample_delete_regional_inventory(): - # Create a client - client = merchant_inventories_v1beta.RegionalInventoryServiceClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.DeleteRegionalInventoryRequest( - name="name_value", - ) - - # Make the request - client.delete_regional_inventory(request=request) - - -# [END merchantapi_v1beta_generated_RegionalInventoryService_DeleteRegionalInventory_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_async.py deleted file mode 100644 index 39a0f6a7e767..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for InsertRegionalInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-inventories - - -# [START merchantapi_v1beta_generated_RegionalInventoryService_InsertRegionalInventory_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_inventories_v1beta - - -async def sample_insert_regional_inventory(): - # Create a client - client = merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient() - - # Initialize request argument(s) - regional_inventory = merchant_inventories_v1beta.RegionalInventory() - regional_inventory.region = "region_value" - - request = merchant_inventories_v1beta.InsertRegionalInventoryRequest( - parent="parent_value", - regional_inventory=regional_inventory, - ) - - # Make the request - response = await client.insert_regional_inventory(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_RegionalInventoryService_InsertRegionalInventory_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_sync.py deleted file mode 100644 index b8b5089a2b83..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for InsertRegionalInventory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-inventories - - -# [START merchantapi_v1beta_generated_RegionalInventoryService_InsertRegionalInventory_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_inventories_v1beta - - -def sample_insert_regional_inventory(): - # Create a client - client = merchant_inventories_v1beta.RegionalInventoryServiceClient() - - # Initialize request argument(s) - regional_inventory = merchant_inventories_v1beta.RegionalInventory() - regional_inventory.region = "region_value" - - request = merchant_inventories_v1beta.InsertRegionalInventoryRequest( - parent="parent_value", - regional_inventory=regional_inventory, - ) - - # Make the request - response = client.insert_regional_inventory(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_RegionalInventoryService_InsertRegionalInventory_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_async.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_async.py deleted file mode 100644 index 33d6df5c8f45..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListRegionalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-inventories - - -# [START merchantapi_v1beta_generated_RegionalInventoryService_ListRegionalInventories_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_inventories_v1beta - - -async def sample_list_regional_inventories(): - # Create a client - client = merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.ListRegionalInventoriesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_regional_inventories(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_RegionalInventoryService_ListRegionalInventories_async] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_sync.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_sync.py deleted file mode 100644 index 7c23ca47ca05..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListRegionalInventories -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-shopping-merchant-inventories - - -# [START merchantapi_v1beta_generated_RegionalInventoryService_ListRegionalInventories_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.shopping import merchant_inventories_v1beta - - -def sample_list_regional_inventories(): - # Create a client - client = merchant_inventories_v1beta.RegionalInventoryServiceClient() - - # Initialize request argument(s) - request = merchant_inventories_v1beta.ListRegionalInventoriesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_regional_inventories(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_RegionalInventoryService_ListRegionalInventories_sync] diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1beta.json b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1beta.json deleted file mode 100644 index 73ddfcf94070..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1beta.json +++ /dev/null @@ -1,953 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.shopping.merchant.inventories.v1beta", - "version": "v1beta" - } - ], - "language": "PYTHON", - "name": "google-shopping-merchant-inventories", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceAsyncClient", - "shortName": "LocalInventoryServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceAsyncClient.delete_local_inventory", - "method": { - "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService.DeleteLocalInventory", - "service": { - "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "shortName": "LocalInventoryService" - }, - "shortName": "DeleteLocalInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_inventories_v1beta.types.DeleteLocalInventoryRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "shortName": "delete_local_inventory" - }, - "description": "Sample for DeleteLocalInventory", - "file": "merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_LocalInventoryService_DeleteLocalInventory_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceClient", - "shortName": "LocalInventoryServiceClient" - }, - "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceClient.delete_local_inventory", - "method": { - "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService.DeleteLocalInventory", - "service": { - "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "shortName": "LocalInventoryService" - }, - "shortName": "DeleteLocalInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_inventories_v1beta.types.DeleteLocalInventoryRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "shortName": "delete_local_inventory" - }, - "description": "Sample for DeleteLocalInventory", - "file": "merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_LocalInventoryService_DeleteLocalInventory_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_local_inventory_service_delete_local_inventory_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceAsyncClient", - "shortName": "LocalInventoryServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceAsyncClient.insert_local_inventory", - "method": { - "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService.InsertLocalInventory", - "service": { - "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "shortName": "LocalInventoryService" - }, - "shortName": "InsertLocalInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_inventories_v1beta.types.InsertLocalInventoryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_inventories_v1beta.types.LocalInventory", - "shortName": "insert_local_inventory" - }, - "description": "Sample for InsertLocalInventory", - "file": "merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_LocalInventoryService_InsertLocalInventory_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceClient", - "shortName": "LocalInventoryServiceClient" - }, - "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceClient.insert_local_inventory", - "method": { - "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService.InsertLocalInventory", - "service": { - "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "shortName": "LocalInventoryService" - }, - "shortName": "InsertLocalInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_inventories_v1beta.types.InsertLocalInventoryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_inventories_v1beta.types.LocalInventory", - "shortName": "insert_local_inventory" - }, - "description": "Sample for InsertLocalInventory", - "file": "merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_LocalInventoryService_InsertLocalInventory_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_local_inventory_service_insert_local_inventory_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceAsyncClient", - "shortName": "LocalInventoryServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceAsyncClient.list_local_inventories", - "method": { - "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService.ListLocalInventories", - "service": { - "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "shortName": "LocalInventoryService" - }, - "shortName": "ListLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_inventories_v1beta.services.local_inventory_service.pagers.ListLocalInventoriesAsyncPager", - "shortName": "list_local_inventories" - }, - "description": "Sample for ListLocalInventories", - "file": "merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_LocalInventoryService_ListLocalInventories_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceClient", - "shortName": "LocalInventoryServiceClient" - }, - "fullName": "google.shopping.merchant_inventories_v1beta.LocalInventoryServiceClient.list_local_inventories", - "method": { - "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService.ListLocalInventories", - "service": { - "fullName": "google.shopping.merchant.inventories.v1beta.LocalInventoryService", - "shortName": "LocalInventoryService" - }, - "shortName": "ListLocalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_inventories_v1beta.types.ListLocalInventoriesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_inventories_v1beta.services.local_inventory_service.pagers.ListLocalInventoriesPager", - "shortName": "list_local_inventories" - }, - "description": "Sample for ListLocalInventories", - "file": "merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_LocalInventoryService_ListLocalInventories_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_local_inventory_service_list_local_inventories_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient", - "shortName": "RegionalInventoryServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient.delete_regional_inventory", - "method": { - "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService.DeleteRegionalInventory", - "service": { - "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "shortName": "RegionalInventoryService" - }, - "shortName": "DeleteRegionalInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_inventories_v1beta.types.DeleteRegionalInventoryRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "shortName": "delete_regional_inventory" - }, - "description": "Sample for DeleteRegionalInventory", - "file": "merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_RegionalInventoryService_DeleteRegionalInventory_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceClient", - "shortName": "RegionalInventoryServiceClient" - }, - "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceClient.delete_regional_inventory", - "method": { - "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService.DeleteRegionalInventory", - "service": { - "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "shortName": "RegionalInventoryService" - }, - "shortName": "DeleteRegionalInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_inventories_v1beta.types.DeleteRegionalInventoryRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "shortName": "delete_regional_inventory" - }, - "description": "Sample for DeleteRegionalInventory", - "file": "merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_RegionalInventoryService_DeleteRegionalInventory_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_regional_inventory_service_delete_regional_inventory_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient", - "shortName": "RegionalInventoryServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient.insert_regional_inventory", - "method": { - "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService.InsertRegionalInventory", - "service": { - "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "shortName": "RegionalInventoryService" - }, - "shortName": "InsertRegionalInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_inventories_v1beta.types.InsertRegionalInventoryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_inventories_v1beta.types.RegionalInventory", - "shortName": "insert_regional_inventory" - }, - "description": "Sample for InsertRegionalInventory", - "file": "merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_RegionalInventoryService_InsertRegionalInventory_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceClient", - "shortName": "RegionalInventoryServiceClient" - }, - "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceClient.insert_regional_inventory", - "method": { - "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService.InsertRegionalInventory", - "service": { - "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "shortName": "RegionalInventoryService" - }, - "shortName": "InsertRegionalInventory" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_inventories_v1beta.types.InsertRegionalInventoryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_inventories_v1beta.types.RegionalInventory", - "shortName": "insert_regional_inventory" - }, - "description": "Sample for InsertRegionalInventory", - "file": "merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_RegionalInventoryService_InsertRegionalInventory_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_regional_inventory_service_insert_regional_inventory_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient", - "shortName": "RegionalInventoryServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceAsyncClient.list_regional_inventories", - "method": { - "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService.ListRegionalInventories", - "service": { - "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "shortName": "RegionalInventoryService" - }, - "shortName": "ListRegionalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.pagers.ListRegionalInventoriesAsyncPager", - "shortName": "list_regional_inventories" - }, - "description": "Sample for ListRegionalInventories", - "file": "merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_RegionalInventoryService_ListRegionalInventories_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceClient", - "shortName": "RegionalInventoryServiceClient" - }, - "fullName": "google.shopping.merchant_inventories_v1beta.RegionalInventoryServiceClient.list_regional_inventories", - "method": { - "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService.ListRegionalInventories", - "service": { - "fullName": "google.shopping.merchant.inventories.v1beta.RegionalInventoryService", - "shortName": "RegionalInventoryService" - }, - "shortName": "ListRegionalInventories" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_inventories_v1beta.types.ListRegionalInventoriesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.pagers.ListRegionalInventoriesPager", - "shortName": "list_regional_inventories" - }, - "description": "Sample for ListRegionalInventories", - "file": "merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_RegionalInventoryService_ListRegionalInventories_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_regional_inventory_service_list_regional_inventories_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/scripts/fixup_merchant_inventories_v1beta_keywords.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/scripts/fixup_merchant_inventories_v1beta_keywords.py deleted file mode 100644 index 02d464643567..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/scripts/fixup_merchant_inventories_v1beta_keywords.py +++ /dev/null @@ -1,181 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class merchant_inventoriesCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'delete_local_inventory': ('name', ), - 'delete_regional_inventory': ('name', ), - 'insert_local_inventory': ('parent', 'local_inventory', ), - 'insert_regional_inventory': ('parent', 'regional_inventory', ), - 'list_local_inventories': ('parent', 'page_size', 'page_token', ), - 'list_regional_inventories': ('parent', 'page_size', 'page_token', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=merchant_inventoriesCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the merchant_inventories client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/setup.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/setup.py deleted file mode 100644 index 4fd17ebb95a5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/setup.py +++ /dev/null @@ -1,99 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import re - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-shopping-merchant-inventories' - - -description = "Google Shopping Merchant Inventories API client library" - -version = None - -with open(os.path.join(package_root, 'google/shopping/merchant_inventories/gapic_version.py')) as fp: - version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) - assert (len(version_candidates) == 1) - version = version_candidates[0] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.1, <3.0.0,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - # Exclude incompatible versions of `google-auth` - # See https://github.com/googleapis/google-cloud-python/issues/12364 - "google-auth >= 2.14.1, <3.0.0,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0", - "proto-plus >= 1.25.0, <2.0.0; python_version >= '3.13'", - "protobuf>=3.20.2,<7.0.0,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", - "google-shopping-type >= 0.1.6, <1.0.0", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-inventories" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.find_namespace_packages() - if package.startswith("google") -] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - extras_require=extras, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.10.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.10.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.11.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.11.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.12.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.12.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.13.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.13.txt deleted file mode 100644 index 0112695e5bbb..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.13.txt +++ /dev/null @@ -1,12 +0,0 @@ -# We use the constraints file for the latest Python version -# (currently this file) to check that the latest -# major versions of dependencies are supported in setup.py. -# List all library dependencies and extras in this file. -# Require the latest major version be installed for each dependency. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# Then this file should have google-cloud-foo>=1 -google-api-core>=2 -google-auth>=2 -proto-plus>=1 -protobuf>=6 -google-shopping-type>=0 diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.7.txt deleted file mode 100644 index 2af887ec8ba0..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.7.txt +++ /dev/null @@ -1,11 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.1 -google-auth==2.14.1 -proto-plus==1.22.3 -protobuf==3.20.2 -google-shopping-type==0.1.6 diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.8.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.8.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.9.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/testing/constraints-3.9.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-shopping-type diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_local_inventory_service.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_local_inventory_service.py deleted file mode 100644 index 91fcbd7af71c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_local_inventory_service.py +++ /dev/null @@ -1,3666 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -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 proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -try: - from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER - HAS_GOOGLE_AUTH_AIO = False - -from google.api_core import 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 -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.oauth2 import service_account -from google.protobuf import timestamp_pb2 # type: ignore -from google.shopping.merchant_inventories_v1beta.services.local_inventory_service import LocalInventoryServiceAsyncClient -from google.shopping.merchant_inventories_v1beta.services.local_inventory_service import LocalInventoryServiceClient -from google.shopping.merchant_inventories_v1beta.services.local_inventory_service import pagers -from google.shopping.merchant_inventories_v1beta.services.local_inventory_service import transports -from google.shopping.merchant_inventories_v1beta.types import localinventory -from google.shopping.type.types import types -from google.type import interval_pb2 # type: ignore -import google.auth - - - -CRED_INFO_JSON = { - "credential_source": "/path/to/file", - "credential_type": "service account credentials", - "principal": "service-account@example.com", -} -CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) - - -async def mock_async_gen(data, chunk_size=1): - for i in range(0, len(data)): # pragma: NO COVER - chunk = data[i : i + chunk_size] - yield chunk.encode("utf-8") - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. -# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. -def async_anonymous_credentials(): - if HAS_GOOGLE_AUTH_AIO: - return ga_credentials_async.AnonymousCredentials() - return ga_credentials.AnonymousCredentials() - -# 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 - -# 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 - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert LocalInventoryServiceClient._get_default_mtls_endpoint(None) is None - assert LocalInventoryServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert LocalInventoryServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert LocalInventoryServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert LocalInventoryServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert LocalInventoryServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert LocalInventoryServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert LocalInventoryServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert LocalInventoryServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - LocalInventoryServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert LocalInventoryServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert LocalInventoryServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert LocalInventoryServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - LocalInventoryServiceClient._read_environment_variables() - 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 LocalInventoryServiceClient._read_environment_variables() == (False, "auto", "foo.com") - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert LocalInventoryServiceClient._get_client_cert_source(None, False) is None - assert LocalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert LocalInventoryServiceClient._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 LocalInventoryServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert LocalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(LocalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceClient)) -@mock.patch.object(LocalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = LocalInventoryServiceClient._DEFAULT_UNIVERSE - default_endpoint = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert LocalInventoryServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert LocalInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - assert LocalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert LocalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "always") == LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - assert LocalInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - assert LocalInventoryServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert LocalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - LocalInventoryServiceClient._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 LocalInventoryServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert LocalInventoryServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert LocalInventoryServiceClient._get_universe_domain(None, None) == LocalInventoryServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - LocalInventoryServiceClient._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) -]) -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) - client = LocalInventoryServiceClient(credentials=cred) - client._transport._credentials = cred - - error = core_exceptions.GoogleAPICallError("message", details=["foo"]) - error.code = error_code - - client._add_cred_info_for_auth_errors(error) - if show_cred_info: - assert error.details == ["foo", CRED_INFO_STRING] - else: - assert error.details == ["foo"] - -@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") - client = LocalInventoryServiceClient(credentials=cred) - client._transport._credentials = cred - - error = core_exceptions.GoogleAPICallError("message", details=[]) - error.code = error_code - - client._add_cred_info_for_auth_errors(error) - assert error.details == [] - -@pytest.mark.parametrize("client_class,transport_name", [ - (LocalInventoryServiceClient, "grpc"), - (LocalInventoryServiceAsyncClient, "grpc_asyncio"), - (LocalInventoryServiceClient, "rest"), -]) -def test_local_inventory_service_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: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'merchantapi.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://merchantapi.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.LocalInventoryServiceGrpcTransport, "grpc"), - (transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.LocalInventoryServiceRestTransport, "rest"), -]) -def test_local_inventory_service_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: - 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", [ - (LocalInventoryServiceClient, "grpc"), - (LocalInventoryServiceAsyncClient, "grpc_asyncio"), - (LocalInventoryServiceClient, "rest"), -]) -def test_local_inventory_service_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: - factory.return_value = creds - 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) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'merchantapi.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://merchantapi.googleapis.com' - ) - - -def test_local_inventory_service_client_get_transport_class(): - transport = LocalInventoryServiceClient.get_transport_class() - available_transports = [ - transports.LocalInventoryServiceGrpcTransport, - transports.LocalInventoryServiceRestTransport, - ] - assert transport in available_transports - - transport = LocalInventoryServiceClient.get_transport_class("grpc") - assert transport == transports.LocalInventoryServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc"), - (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest"), -]) -@mock.patch.object(LocalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceClient)) -@mock.patch.object(LocalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceAsyncClient)) -def test_local_inventory_service_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(LocalInventoryServiceClient, '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(LocalInventoryServiceClient, '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: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - 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=None, - ) - - # 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: - 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), - 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=None, - ) - - # 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: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - 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=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) 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`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - 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: - 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), - 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", [ - (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc", "true"), - (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc", "false"), - (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest", "true"), - (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(LocalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceClient)) -@mock.patch.object(LocalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_local_inventory_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, 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) - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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): - if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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): - 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), - 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=None, - ) - - -@pytest.mark.parametrize("client_class", [ - LocalInventoryServiceClient, LocalInventoryServiceAsyncClient -]) -@mock.patch.object(LocalInventoryServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LocalInventoryServiceClient)) -@mock.patch.object(LocalInventoryServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LocalInventoryServiceAsyncClient)) -def test_local_inventory_service_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) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - 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) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - 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 "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # 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): - 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() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) 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`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - -@pytest.mark.parametrize("client_class", [ - LocalInventoryServiceClient, LocalInventoryServiceAsyncClient -]) -@mock.patch.object(LocalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceClient)) -@mock.patch.object(LocalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceAsyncClient)) -def test_local_inventory_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = LocalInventoryServiceClient._DEFAULT_UNIVERSE - default_endpoint = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = LocalInventoryServiceClient._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()) - assert client.api_endpoint == api_override - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", - # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - - # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), - # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, - # and ClientOptions.universe_domain="bar.com", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. - options = client_options.ClientOptions() - 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()) - 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) - - # 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. - options = client_options.ClientOptions() - 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()) - assert client.api_endpoint == default_endpoint - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc"), - (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest"), -]) -def test_local_inventory_service_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: - 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), - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc", grpc_helpers), - (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest", None), -]) -def test_local_inventory_service_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" - ) - - 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), - 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=None, - ) - -def test_local_inventory_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_inventories_v1beta.services.local_inventory_service.transports.LocalInventoryServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = LocalInventoryServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - 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=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc", grpc_helpers), - (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_local_inventory_service_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" - ) - - 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), - 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=None, - ) - - # 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: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "merchantapi.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/content', -), - scopes=None, - default_host="merchantapi.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - localinventory.ListLocalInventoriesRequest, - dict, -]) -def test_list_local_inventories(request_type, transport: str = 'grpc'): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = localinventory.ListLocalInventoriesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = localinventory.ListLocalInventoriesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListLocalInventoriesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_local_inventories_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = localinventory.ListLocalInventoriesRequest( - 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_local_inventories), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_local_inventories(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == localinventory.ListLocalInventoriesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_local_inventories_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_local_inventories in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_local_inventories] = mock_rpc - request = {} - client.list_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_local_inventories(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_local_inventories_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_local_inventories 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_local_inventories] = mock_rpc - - request = {} - await client.list_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_local_inventories(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_local_inventories_async(transport: str = 'grpc_asyncio', request_type=localinventory.ListLocalInventoriesRequest): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(localinventory.ListLocalInventoriesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = localinventory.ListLocalInventoriesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListLocalInventoriesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_local_inventories_async_from_dict(): - await test_list_local_inventories_async(request_type=dict) - -def test_list_local_inventories_field_headers(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = localinventory.ListLocalInventoriesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__') as call: - call.return_value = localinventory.ListLocalInventoriesResponse() - client.list_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_local_inventories_field_headers_async(): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = localinventory.ListLocalInventoriesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.ListLocalInventoriesResponse()) - await client.list_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_local_inventories_flattened(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = localinventory.ListLocalInventoriesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_local_inventories( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_local_inventories_flattened_error(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_local_inventories( - localinventory.ListLocalInventoriesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_local_inventories_flattened_async(): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = localinventory.ListLocalInventoriesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.ListLocalInventoriesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_local_inventories( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_local_inventories_flattened_error_async(): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_local_inventories( - localinventory.ListLocalInventoriesRequest(), - parent='parent_value', - ) - - -def test_list_local_inventories_pager(transport_name: str = "grpc"): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - localinventory.LocalInventory(), - localinventory.LocalInventory(), - ], - next_page_token='abc', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[], - next_page_token='def', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - ], - next_page_token='ghi', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - localinventory.LocalInventory(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_local_inventories(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, localinventory.LocalInventory) - for i in results) -def test_list_local_inventories_pages(transport_name: str = "grpc"): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - localinventory.LocalInventory(), - localinventory.LocalInventory(), - ], - next_page_token='abc', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[], - next_page_token='def', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - ], - next_page_token='ghi', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - localinventory.LocalInventory(), - ], - ), - RuntimeError, - ) - pages = list(client.list_local_inventories(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_local_inventories_async_pager(): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - localinventory.LocalInventory(), - localinventory.LocalInventory(), - ], - next_page_token='abc', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[], - next_page_token='def', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - ], - next_page_token='ghi', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - localinventory.LocalInventory(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_local_inventories(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, localinventory.LocalInventory) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_local_inventories_async_pages(): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - localinventory.LocalInventory(), - localinventory.LocalInventory(), - ], - next_page_token='abc', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[], - next_page_token='def', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - ], - next_page_token='ghi', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - localinventory.LocalInventory(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_local_inventories(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - localinventory.InsertLocalInventoryRequest, - dict, -]) -def test_insert_local_inventory(request_type, transport: str = 'grpc'): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_local_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = localinventory.LocalInventory( - name='name_value', - account=749, - store_code='store_code_value', - availability='availability_value', - quantity=895, - pickup_method='pickup_method_value', - pickup_sla='pickup_sla_value', - instore_product_location='instore_product_location_value', - ) - response = client.insert_local_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = localinventory.InsertLocalInventoryRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, localinventory.LocalInventory) - assert response.name == 'name_value' - assert response.account == 749 - assert response.store_code == 'store_code_value' - assert response.availability == 'availability_value' - assert response.quantity == 895 - assert response.pickup_method == 'pickup_method_value' - assert response.pickup_sla == 'pickup_sla_value' - assert response.instore_product_location == 'instore_product_location_value' - - -def test_insert_local_inventory_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = localinventory.InsertLocalInventoryRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_local_inventory), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.insert_local_inventory(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == localinventory.InsertLocalInventoryRequest( - parent='parent_value', - ) - -def test_insert_local_inventory_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.insert_local_inventory in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.insert_local_inventory] = mock_rpc - request = {} - client.insert_local_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.insert_local_inventory(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_insert_local_inventory_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.insert_local_inventory 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.insert_local_inventory] = mock_rpc - - request = {} - await client.insert_local_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.insert_local_inventory(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_insert_local_inventory_async(transport: str = 'grpc_asyncio', request_type=localinventory.InsertLocalInventoryRequest): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_local_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(localinventory.LocalInventory( - name='name_value', - account=749, - store_code='store_code_value', - availability='availability_value', - quantity=895, - pickup_method='pickup_method_value', - pickup_sla='pickup_sla_value', - instore_product_location='instore_product_location_value', - )) - response = await client.insert_local_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = localinventory.InsertLocalInventoryRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, localinventory.LocalInventory) - assert response.name == 'name_value' - assert response.account == 749 - assert response.store_code == 'store_code_value' - assert response.availability == 'availability_value' - assert response.quantity == 895 - assert response.pickup_method == 'pickup_method_value' - assert response.pickup_sla == 'pickup_sla_value' - assert response.instore_product_location == 'instore_product_location_value' - - -@pytest.mark.asyncio -async def test_insert_local_inventory_async_from_dict(): - await test_insert_local_inventory_async(request_type=dict) - -def test_insert_local_inventory_field_headers(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = localinventory.InsertLocalInventoryRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_local_inventory), - '__call__') as call: - call.return_value = localinventory.LocalInventory() - client.insert_local_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_insert_local_inventory_field_headers_async(): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = localinventory.InsertLocalInventoryRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_local_inventory), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.LocalInventory()) - await client.insert_local_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - localinventory.DeleteLocalInventoryRequest, - dict, -]) -def test_delete_local_inventory(request_type, transport: str = 'grpc'): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_local_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_local_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = localinventory.DeleteLocalInventoryRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_local_inventory_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = localinventory.DeleteLocalInventoryRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_local_inventory), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_local_inventory(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == localinventory.DeleteLocalInventoryRequest( - name='name_value', - ) - -def test_delete_local_inventory_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_local_inventory in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_local_inventory] = mock_rpc - request = {} - client.delete_local_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_local_inventory(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_local_inventory_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.delete_local_inventory 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_local_inventory] = mock_rpc - - request = {} - await client.delete_local_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_local_inventory(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_local_inventory_async(transport: str = 'grpc_asyncio', request_type=localinventory.DeleteLocalInventoryRequest): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_local_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_local_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = localinventory.DeleteLocalInventoryRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_local_inventory_async_from_dict(): - await test_delete_local_inventory_async(request_type=dict) - -def test_delete_local_inventory_field_headers(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = localinventory.DeleteLocalInventoryRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_local_inventory), - '__call__') as call: - call.return_value = None - client.delete_local_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_local_inventory_field_headers_async(): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = localinventory.DeleteLocalInventoryRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_local_inventory), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_local_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_local_inventory_flattened(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_local_inventory), - '__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_local_inventory( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_local_inventory_flattened_error(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_local_inventory( - localinventory.DeleteLocalInventoryRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_local_inventory_flattened_async(): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_local_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_local_inventory( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_local_inventory_flattened_error_async(): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_local_inventory( - localinventory.DeleteLocalInventoryRequest(), - name='name_value', - ) - - -def test_list_local_inventories_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_local_inventories in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_local_inventories] = mock_rpc - - request = {} - client.list_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_local_inventories(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_local_inventories_rest_required_fields(request_type=localinventory.ListLocalInventoriesRequest): - transport_class = transports.LocalInventoryServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_local_inventories._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_local_inventories._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", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = localinventory.ListLocalInventoriesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = localinventory.ListLocalInventoriesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_local_inventories(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_local_inventories_rest_unset_required_fields(): - transport = transports.LocalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_local_inventories._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_local_inventories_rest_flattened(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = localinventory.ListLocalInventoriesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1/products/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = localinventory.ListLocalInventoriesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.list_local_inventories(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/inventories/v1beta/{parent=accounts/*/products/*}/localInventories" % client.transport._host, args[1]) - - -def test_list_local_inventories_rest_flattened_error(transport: str = 'rest'): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_local_inventories( - localinventory.ListLocalInventoriesRequest(), - parent='parent_value', - ) - - -def test_list_local_inventories_rest_pager(transport: str = 'rest'): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - localinventory.LocalInventory(), - localinventory.LocalInventory(), - ], - next_page_token='abc', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[], - next_page_token='def', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - ], - next_page_token='ghi', - ), - localinventory.ListLocalInventoriesResponse( - local_inventories=[ - localinventory.LocalInventory(), - localinventory.LocalInventory(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(localinventory.ListLocalInventoriesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'accounts/sample1/products/sample2'} - - pager = client.list_local_inventories(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, localinventory.LocalInventory) - for i in results) - - pages = list(client.list_local_inventories(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_insert_local_inventory_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.insert_local_inventory in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.insert_local_inventory] = mock_rpc - - request = {} - client.insert_local_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.insert_local_inventory(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_insert_local_inventory_rest_required_fields(request_type=localinventory.InsertLocalInventoryRequest): - transport_class = transports.LocalInventoryServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).insert_local_inventory._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).insert_local_inventory._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = localinventory.LocalInventory() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = localinventory.LocalInventory.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.insert_local_inventory(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_insert_local_inventory_rest_unset_required_fields(): - transport = transports.LocalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.insert_local_inventory._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "localInventory", ))) - - -def test_delete_local_inventory_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_local_inventory in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_local_inventory] = mock_rpc - - request = {} - client.delete_local_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_local_inventory(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_delete_local_inventory_rest_required_fields(request_type=localinventory.DeleteLocalInventoryRequest): - transport_class = transports.LocalInventoryServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_local_inventory._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_local_inventory._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.delete_local_inventory(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_local_inventory_rest_unset_required_fields(): - transport = transports.LocalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_local_inventory._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_local_inventory_rest_flattened(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/products/sample2/localInventories/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.delete_local_inventory(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/inventories/v1beta/{name=accounts/*/products/*/localInventories/*}" % client.transport._host, args[1]) - - -def test_delete_local_inventory_rest_flattened_error(transport: str = 'rest'): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_local_inventory( - localinventory.DeleteLocalInventoryRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.LocalInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.LocalInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LocalInventoryServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.LocalInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = LocalInventoryServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = LocalInventoryServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.LocalInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LocalInventoryServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.LocalInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = LocalInventoryServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.LocalInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.LocalInventoryServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.LocalInventoryServiceGrpcTransport, - transports.LocalInventoryServiceGrpcAsyncIOTransport, - transports.LocalInventoryServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_kind_grpc(): - transport = LocalInventoryServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_local_inventories_empty_call_grpc(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__') as call: - call.return_value = localinventory.ListLocalInventoriesResponse() - client.list_local_inventories(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = localinventory.ListLocalInventoriesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_insert_local_inventory_empty_call_grpc(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_local_inventory), - '__call__') as call: - call.return_value = localinventory.LocalInventory() - client.insert_local_inventory(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = localinventory.InsertLocalInventoryRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_local_inventory_empty_call_grpc(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_local_inventory), - '__call__') as call: - call.return_value = None - client.delete_local_inventory(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = localinventory.DeleteLocalInventoryRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = LocalInventoryServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_local_inventories_empty_call_grpc_asyncio(): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.ListLocalInventoriesResponse( - next_page_token='next_page_token_value', - )) - await client.list_local_inventories(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = localinventory.ListLocalInventoriesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_insert_local_inventory_empty_call_grpc_asyncio(): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_local_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.LocalInventory( - name='name_value', - account=749, - store_code='store_code_value', - availability='availability_value', - quantity=895, - pickup_method='pickup_method_value', - pickup_sla='pickup_sla_value', - instore_product_location='instore_product_location_value', - )) - await client.insert_local_inventory(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = localinventory.InsertLocalInventoryRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_local_inventory_empty_call_grpc_asyncio(): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_local_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_local_inventory(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = localinventory.DeleteLocalInventoryRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = LocalInventoryServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_list_local_inventories_rest_bad_request(request_type=localinventory.ListLocalInventoriesRequest): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/products/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_local_inventories(request) - - -@pytest.mark.parametrize("request_type", [ - localinventory.ListLocalInventoriesRequest, - dict, -]) -def test_list_local_inventories_rest_call_success(request_type): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/products/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = localinventory.ListLocalInventoriesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = localinventory.ListLocalInventoriesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_local_inventories(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListLocalInventoriesPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_local_inventories_rest_interceptors(null_interceptor): - transport = transports.LocalInventoryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.LocalInventoryServiceRestInterceptor(), - ) - client = LocalInventoryServiceClient(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.LocalInventoryServiceRestInterceptor, "post_list_local_inventories") as post, \ - mock.patch.object(transports.LocalInventoryServiceRestInterceptor, "post_list_local_inventories_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.LocalInventoryServiceRestInterceptor, "pre_list_local_inventories") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = localinventory.ListLocalInventoriesRequest.pb(localinventory.ListLocalInventoriesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = localinventory.ListLocalInventoriesResponse.to_json(localinventory.ListLocalInventoriesResponse()) - req.return_value.content = return_value - - request = localinventory.ListLocalInventoriesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = localinventory.ListLocalInventoriesResponse() - post_with_metadata.return_value = localinventory.ListLocalInventoriesResponse(), metadata - - client.list_local_inventories(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_insert_local_inventory_rest_bad_request(request_type=localinventory.InsertLocalInventoryRequest): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/products/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.insert_local_inventory(request) - - -@pytest.mark.parametrize("request_type", [ - localinventory.InsertLocalInventoryRequest, - dict, -]) -def test_insert_local_inventory_rest_call_success(request_type): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/products/sample2'} - request_init["local_inventory"] = {'name': 'name_value', 'account': 749, 'store_code': 'store_code_value', 'price': {'amount_micros': 1408, 'currency_code': 'currency_code_value'}, 'sale_price': {}, 'sale_price_effective_date': {'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}}, 'availability': 'availability_value', 'quantity': 895, 'pickup_method': 'pickup_method_value', 'pickup_sla': 'pickup_sla_value', 'instore_product_location': 'instore_product_location_value', 'custom_attributes': [{'name': 'name_value', 'value': 'value_value', 'group_values': {}}]} - # 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 = localinventory.InsertLocalInventoryRequest.meta.fields["local_inventory"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["local_inventory"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["local_inventory"][field])): - del request_init["local_inventory"][field][i][subfield] - else: - del request_init["local_inventory"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = localinventory.LocalInventory( - name='name_value', - account=749, - store_code='store_code_value', - availability='availability_value', - quantity=895, - pickup_method='pickup_method_value', - pickup_sla='pickup_sla_value', - instore_product_location='instore_product_location_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = localinventory.LocalInventory.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.insert_local_inventory(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, localinventory.LocalInventory) - assert response.name == 'name_value' - assert response.account == 749 - assert response.store_code == 'store_code_value' - assert response.availability == 'availability_value' - assert response.quantity == 895 - assert response.pickup_method == 'pickup_method_value' - assert response.pickup_sla == 'pickup_sla_value' - assert response.instore_product_location == 'instore_product_location_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_insert_local_inventory_rest_interceptors(null_interceptor): - transport = transports.LocalInventoryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.LocalInventoryServiceRestInterceptor(), - ) - client = LocalInventoryServiceClient(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.LocalInventoryServiceRestInterceptor, "post_insert_local_inventory") as post, \ - mock.patch.object(transports.LocalInventoryServiceRestInterceptor, "post_insert_local_inventory_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.LocalInventoryServiceRestInterceptor, "pre_insert_local_inventory") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = localinventory.InsertLocalInventoryRequest.pb(localinventory.InsertLocalInventoryRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = localinventory.LocalInventory.to_json(localinventory.LocalInventory()) - req.return_value.content = return_value - - request = localinventory.InsertLocalInventoryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = localinventory.LocalInventory() - post_with_metadata.return_value = localinventory.LocalInventory(), metadata - - client.insert_local_inventory(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_local_inventory_rest_bad_request(request_type=localinventory.DeleteLocalInventoryRequest): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/products/sample2/localInventories/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_local_inventory(request) - - -@pytest.mark.parametrize("request_type", [ - localinventory.DeleteLocalInventoryRequest, - dict, -]) -def test_delete_local_inventory_rest_call_success(request_type): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/products/sample2/localInventories/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = '' - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_local_inventory(request) - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_local_inventory_rest_interceptors(null_interceptor): - transport = transports.LocalInventoryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.LocalInventoryServiceRestInterceptor(), - ) - client = LocalInventoryServiceClient(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.LocalInventoryServiceRestInterceptor, "pre_delete_local_inventory") as pre: - pre.assert_not_called() - pb_message = localinventory.DeleteLocalInventoryRequest.pb(localinventory.DeleteLocalInventoryRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - request = localinventory.DeleteLocalInventoryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_local_inventory(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - -def test_initialize_client_w_rest(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_local_inventories_empty_call_rest(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__') as call: - client.list_local_inventories(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = localinventory.ListLocalInventoriesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_insert_local_inventory_empty_call_rest(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_local_inventory), - '__call__') as call: - client.insert_local_inventory(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = localinventory.InsertLocalInventoryRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_local_inventory_empty_call_rest(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_local_inventory), - '__call__') as call: - client.delete_local_inventory(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = localinventory.DeleteLocalInventoryRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.LocalInventoryServiceGrpcTransport, - ) - -def test_local_inventory_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.LocalInventoryServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_local_inventory_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_inventories_v1beta.services.local_inventory_service.transports.LocalInventoryServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.LocalInventoryServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_local_inventories', - 'insert_local_inventory', - 'delete_local_inventory', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_local_inventory_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.shopping.merchant_inventories_v1beta.services.local_inventory_service.transports.LocalInventoryServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LocalInventoryServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/content', -), - quota_project_id="octopus", - ) - - -def test_local_inventory_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.shopping.merchant_inventories_v1beta.services.local_inventory_service.transports.LocalInventoryServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LocalInventoryServiceTransport() - adc.assert_called_once() - - -def test_local_inventory_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - LocalInventoryServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/content', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.LocalInventoryServiceGrpcTransport, - transports.LocalInventoryServiceGrpcAsyncIOTransport, - ], -) -def test_local_inventory_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/content',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.LocalInventoryServiceGrpcTransport, - transports.LocalInventoryServiceGrpcAsyncIOTransport, - transports.LocalInventoryServiceRestTransport, - ], -) -def test_local_inventory_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.LocalInventoryServiceGrpcTransport, grpc_helpers), - (transports.LocalInventoryServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_local_inventory_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "merchantapi.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/content', -), - scopes=["1", "2"], - default_host="merchantapi.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.LocalInventoryServiceGrpcTransport, transports.LocalInventoryServiceGrpcAsyncIOTransport]) -def test_local_inventory_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_local_inventory_service_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.LocalInventoryServiceRestTransport ( - 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", -]) -def test_local_inventory_service_host_no_port(transport_name): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='merchantapi.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'merchantapi.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://merchantapi.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_local_inventory_service_host_with_port(transport_name): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='merchantapi.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'merchantapi.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://merchantapi.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_local_inventory_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = LocalInventoryServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = LocalInventoryServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_local_inventories._session - session2 = client2.transport.list_local_inventories._session - assert session1 != session2 - session1 = client1.transport.insert_local_inventory._session - session2 = client2.transport.insert_local_inventory._session - assert session1 != session2 - session1 = client1.transport.delete_local_inventory._session - session2 = client2.transport.delete_local_inventory._session - assert session1 != session2 -def test_local_inventory_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.LocalInventoryServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_local_inventory_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.LocalInventoryServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.LocalInventoryServiceGrpcTransport, transports.LocalInventoryServiceGrpcAsyncIOTransport]) -def test_local_inventory_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.LocalInventoryServiceGrpcTransport, transports.LocalInventoryServiceGrpcAsyncIOTransport]) -def test_local_inventory_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_local_inventory_path(): - account = "squid" - product = "clam" - store_code = "whelk" - expected = "accounts/{account}/products/{product}/localInventories/{store_code}".format(account=account, product=product, store_code=store_code, ) - actual = LocalInventoryServiceClient.local_inventory_path(account, product, store_code) - assert expected == actual - - -def test_parse_local_inventory_path(): - expected = { - "account": "octopus", - "product": "oyster", - "store_code": "nudibranch", - } - path = LocalInventoryServiceClient.local_inventory_path(**expected) - - # Check that the path construction is reversible. - actual = LocalInventoryServiceClient.parse_local_inventory_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = LocalInventoryServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = LocalInventoryServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = LocalInventoryServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = LocalInventoryServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = LocalInventoryServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = LocalInventoryServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = LocalInventoryServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = LocalInventoryServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = LocalInventoryServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = LocalInventoryServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = LocalInventoryServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = LocalInventoryServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = LocalInventoryServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = LocalInventoryServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = LocalInventoryServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.LocalInventoryServiceTransport, '_prep_wrapped_messages') as prep: - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.LocalInventoryServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = LocalInventoryServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -def test_transport_close_grpc(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -@pytest.mark.asyncio -async def test_transport_close_grpc_asyncio(): - client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close_rest(): - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport), - (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - 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=None, - ) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_regional_inventory_service.py b/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_regional_inventory_service.py deleted file mode 100644 index a9aec23ea1e3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/tests/unit/gapic/merchant_inventories_v1beta/test_regional_inventory_service.py +++ /dev/null @@ -1,3638 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -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 proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -try: - from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER - HAS_GOOGLE_AUTH_AIO = False - -from google.api_core import 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 -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.oauth2 import service_account -from google.protobuf import timestamp_pb2 # type: ignore -from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service import RegionalInventoryServiceAsyncClient -from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service import RegionalInventoryServiceClient -from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service import pagers -from google.shopping.merchant_inventories_v1beta.services.regional_inventory_service import transports -from google.shopping.merchant_inventories_v1beta.types import regionalinventory -from google.shopping.type.types import types -from google.type import interval_pb2 # type: ignore -import google.auth - - - -CRED_INFO_JSON = { - "credential_source": "/path/to/file", - "credential_type": "service account credentials", - "principal": "service-account@example.com", -} -CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) - - -async def mock_async_gen(data, chunk_size=1): - for i in range(0, len(data)): # pragma: NO COVER - chunk = data[i : i + chunk_size] - yield chunk.encode("utf-8") - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. -# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. -def async_anonymous_credentials(): - if HAS_GOOGLE_AUTH_AIO: - return ga_credentials_async.AnonymousCredentials() - return ga_credentials.AnonymousCredentials() - -# 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 - -# 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 - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert RegionalInventoryServiceClient._get_default_mtls_endpoint(None) is None - assert RegionalInventoryServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert RegionalInventoryServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert RegionalInventoryServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert RegionalInventoryServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert RegionalInventoryServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert RegionalInventoryServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert RegionalInventoryServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert RegionalInventoryServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - RegionalInventoryServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert RegionalInventoryServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert RegionalInventoryServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert RegionalInventoryServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - RegionalInventoryServiceClient._read_environment_variables() - 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 RegionalInventoryServiceClient._read_environment_variables() == (False, "auto", "foo.com") - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert RegionalInventoryServiceClient._get_client_cert_source(None, False) is None - assert RegionalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert RegionalInventoryServiceClient._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 RegionalInventoryServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert RegionalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(RegionalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceClient)) -@mock.patch.object(RegionalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = RegionalInventoryServiceClient._DEFAULT_UNIVERSE - default_endpoint = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert RegionalInventoryServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert RegionalInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - assert RegionalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert RegionalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "always") == RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - assert RegionalInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - assert RegionalInventoryServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert RegionalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - RegionalInventoryServiceClient._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 RegionalInventoryServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert RegionalInventoryServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert RegionalInventoryServiceClient._get_universe_domain(None, None) == RegionalInventoryServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - RegionalInventoryServiceClient._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) -]) -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) - client = RegionalInventoryServiceClient(credentials=cred) - client._transport._credentials = cred - - error = core_exceptions.GoogleAPICallError("message", details=["foo"]) - error.code = error_code - - client._add_cred_info_for_auth_errors(error) - if show_cred_info: - assert error.details == ["foo", CRED_INFO_STRING] - else: - assert error.details == ["foo"] - -@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") - client = RegionalInventoryServiceClient(credentials=cred) - client._transport._credentials = cred - - error = core_exceptions.GoogleAPICallError("message", details=[]) - error.code = error_code - - client._add_cred_info_for_auth_errors(error) - assert error.details == [] - -@pytest.mark.parametrize("client_class,transport_name", [ - (RegionalInventoryServiceClient, "grpc"), - (RegionalInventoryServiceAsyncClient, "grpc_asyncio"), - (RegionalInventoryServiceClient, "rest"), -]) -def test_regional_inventory_service_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: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'merchantapi.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://merchantapi.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.RegionalInventoryServiceGrpcTransport, "grpc"), - (transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.RegionalInventoryServiceRestTransport, "rest"), -]) -def test_regional_inventory_service_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: - 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", [ - (RegionalInventoryServiceClient, "grpc"), - (RegionalInventoryServiceAsyncClient, "grpc_asyncio"), - (RegionalInventoryServiceClient, "rest"), -]) -def test_regional_inventory_service_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: - factory.return_value = creds - 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) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'merchantapi.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://merchantapi.googleapis.com' - ) - - -def test_regional_inventory_service_client_get_transport_class(): - transport = RegionalInventoryServiceClient.get_transport_class() - available_transports = [ - transports.RegionalInventoryServiceGrpcTransport, - transports.RegionalInventoryServiceRestTransport, - ] - assert transport in available_transports - - transport = RegionalInventoryServiceClient.get_transport_class("grpc") - assert transport == transports.RegionalInventoryServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc"), - (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest"), -]) -@mock.patch.object(RegionalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceClient)) -@mock.patch.object(RegionalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceAsyncClient)) -def test_regional_inventory_service_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(RegionalInventoryServiceClient, '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(RegionalInventoryServiceClient, '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: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - 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=None, - ) - - # 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: - 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), - 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=None, - ) - - # 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: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - 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=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) 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`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - 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: - 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), - 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", [ - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc", "true"), - (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc", "false"), - (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest", "true"), - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(RegionalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceClient)) -@mock.patch.object(RegionalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_regional_inventory_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, 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) - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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): - if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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): - 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), - 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=None, - ) - - -@pytest.mark.parametrize("client_class", [ - RegionalInventoryServiceClient, RegionalInventoryServiceAsyncClient -]) -@mock.patch.object(RegionalInventoryServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegionalInventoryServiceClient)) -@mock.patch.object(RegionalInventoryServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegionalInventoryServiceAsyncClient)) -def test_regional_inventory_service_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) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - 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) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - 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 "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # 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): - 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() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) 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`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - -@pytest.mark.parametrize("client_class", [ - RegionalInventoryServiceClient, RegionalInventoryServiceAsyncClient -]) -@mock.patch.object(RegionalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceClient)) -@mock.patch.object(RegionalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceAsyncClient)) -def test_regional_inventory_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = RegionalInventoryServiceClient._DEFAULT_UNIVERSE - default_endpoint = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = RegionalInventoryServiceClient._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()) - assert client.api_endpoint == api_override - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", - # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - - # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), - # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, - # and ClientOptions.universe_domain="bar.com", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. - options = client_options.ClientOptions() - 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()) - 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) - - # 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. - options = client_options.ClientOptions() - 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()) - assert client.api_endpoint == default_endpoint - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc"), - (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest"), -]) -def test_regional_inventory_service_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: - 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), - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc", grpc_helpers), - (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest", None), -]) -def test_regional_inventory_service_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" - ) - - 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), - 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=None, - ) - -def test_regional_inventory_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.transports.RegionalInventoryServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = RegionalInventoryServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - 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=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc", grpc_helpers), - (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_regional_inventory_service_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" - ) - - 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), - 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=None, - ) - - # 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: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "merchantapi.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/content', -), - scopes=None, - default_host="merchantapi.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - regionalinventory.ListRegionalInventoriesRequest, - dict, -]) -def test_list_regional_inventories(request_type, transport: str = 'grpc'): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = regionalinventory.ListRegionalInventoriesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_regional_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = regionalinventory.ListRegionalInventoriesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListRegionalInventoriesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_regional_inventories_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = regionalinventory.ListRegionalInventoriesRequest( - 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_regional_inventories), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_regional_inventories(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == regionalinventory.ListRegionalInventoriesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_regional_inventories_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_regional_inventories in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_regional_inventories] = mock_rpc - request = {} - client.list_regional_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_regional_inventories(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_regional_inventories_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_regional_inventories 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_regional_inventories] = mock_rpc - - request = {} - await client.list_regional_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_regional_inventories(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_regional_inventories_async(transport: str = 'grpc_asyncio', request_type=regionalinventory.ListRegionalInventoriesRequest): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.ListRegionalInventoriesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_regional_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = regionalinventory.ListRegionalInventoriesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListRegionalInventoriesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_regional_inventories_async_from_dict(): - await test_list_regional_inventories_async(request_type=dict) - -def test_list_regional_inventories_field_headers(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = regionalinventory.ListRegionalInventoriesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__') as call: - call.return_value = regionalinventory.ListRegionalInventoriesResponse() - client.list_regional_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_regional_inventories_field_headers_async(): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = regionalinventory.ListRegionalInventoriesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.ListRegionalInventoriesResponse()) - await client.list_regional_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_regional_inventories_flattened(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = regionalinventory.ListRegionalInventoriesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_regional_inventories( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_regional_inventories_flattened_error(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_regional_inventories( - regionalinventory.ListRegionalInventoriesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_regional_inventories_flattened_async(): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = regionalinventory.ListRegionalInventoriesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.ListRegionalInventoriesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_regional_inventories( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_regional_inventories_flattened_error_async(): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_regional_inventories( - regionalinventory.ListRegionalInventoriesRequest(), - parent='parent_value', - ) - - -def test_list_regional_inventories_pager(transport_name: str = "grpc"): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - ], - next_page_token='abc', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[], - next_page_token='def', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - ], - next_page_token='ghi', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_regional_inventories(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, regionalinventory.RegionalInventory) - for i in results) -def test_list_regional_inventories_pages(transport_name: str = "grpc"): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - ], - next_page_token='abc', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[], - next_page_token='def', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - ], - next_page_token='ghi', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - ], - ), - RuntimeError, - ) - pages = list(client.list_regional_inventories(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_regional_inventories_async_pager(): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - ], - next_page_token='abc', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[], - next_page_token='def', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - ], - next_page_token='ghi', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_regional_inventories(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, regionalinventory.RegionalInventory) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_regional_inventories_async_pages(): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - ], - next_page_token='abc', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[], - next_page_token='def', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - ], - next_page_token='ghi', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_regional_inventories(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - regionalinventory.InsertRegionalInventoryRequest, - dict, -]) -def test_insert_regional_inventory(request_type, transport: str = 'grpc'): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_regional_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = regionalinventory.RegionalInventory( - name='name_value', - account=749, - region='region_value', - availability='availability_value', - ) - response = client.insert_regional_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = regionalinventory.InsertRegionalInventoryRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, regionalinventory.RegionalInventory) - assert response.name == 'name_value' - assert response.account == 749 - assert response.region == 'region_value' - assert response.availability == 'availability_value' - - -def test_insert_regional_inventory_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = regionalinventory.InsertRegionalInventoryRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_regional_inventory), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.insert_regional_inventory(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == regionalinventory.InsertRegionalInventoryRequest( - parent='parent_value', - ) - -def test_insert_regional_inventory_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.insert_regional_inventory in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.insert_regional_inventory] = mock_rpc - request = {} - client.insert_regional_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.insert_regional_inventory(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_insert_regional_inventory_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.insert_regional_inventory 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.insert_regional_inventory] = mock_rpc - - request = {} - await client.insert_regional_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.insert_regional_inventory(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_insert_regional_inventory_async(transport: str = 'grpc_asyncio', request_type=regionalinventory.InsertRegionalInventoryRequest): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_regional_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.RegionalInventory( - name='name_value', - account=749, - region='region_value', - availability='availability_value', - )) - response = await client.insert_regional_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = regionalinventory.InsertRegionalInventoryRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, regionalinventory.RegionalInventory) - assert response.name == 'name_value' - assert response.account == 749 - assert response.region == 'region_value' - assert response.availability == 'availability_value' - - -@pytest.mark.asyncio -async def test_insert_regional_inventory_async_from_dict(): - await test_insert_regional_inventory_async(request_type=dict) - -def test_insert_regional_inventory_field_headers(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = regionalinventory.InsertRegionalInventoryRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_regional_inventory), - '__call__') as call: - call.return_value = regionalinventory.RegionalInventory() - client.insert_regional_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_insert_regional_inventory_field_headers_async(): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = regionalinventory.InsertRegionalInventoryRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_regional_inventory), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.RegionalInventory()) - await client.insert_regional_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - regionalinventory.DeleteRegionalInventoryRequest, - dict, -]) -def test_delete_regional_inventory(request_type, transport: str = 'grpc'): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_regional_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_regional_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = regionalinventory.DeleteRegionalInventoryRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_regional_inventory_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = regionalinventory.DeleteRegionalInventoryRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_regional_inventory), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_regional_inventory(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == regionalinventory.DeleteRegionalInventoryRequest( - name='name_value', - ) - -def test_delete_regional_inventory_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_regional_inventory in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_regional_inventory] = mock_rpc - request = {} - client.delete_regional_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_regional_inventory(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_regional_inventory_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.delete_regional_inventory 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_regional_inventory] = mock_rpc - - request = {} - await client.delete_regional_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_regional_inventory(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_regional_inventory_async(transport: str = 'grpc_asyncio', request_type=regionalinventory.DeleteRegionalInventoryRequest): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_regional_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_regional_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = regionalinventory.DeleteRegionalInventoryRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_regional_inventory_async_from_dict(): - await test_delete_regional_inventory_async(request_type=dict) - -def test_delete_regional_inventory_field_headers(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = regionalinventory.DeleteRegionalInventoryRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_regional_inventory), - '__call__') as call: - call.return_value = None - client.delete_regional_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_regional_inventory_field_headers_async(): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = regionalinventory.DeleteRegionalInventoryRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_regional_inventory), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_regional_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_regional_inventory_flattened(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_regional_inventory), - '__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_regional_inventory( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_regional_inventory_flattened_error(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_regional_inventory( - regionalinventory.DeleteRegionalInventoryRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_regional_inventory_flattened_async(): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_regional_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_regional_inventory( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_regional_inventory_flattened_error_async(): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_regional_inventory( - regionalinventory.DeleteRegionalInventoryRequest(), - name='name_value', - ) - - -def test_list_regional_inventories_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_regional_inventories in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_regional_inventories] = mock_rpc - - request = {} - client.list_regional_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_regional_inventories(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_regional_inventories_rest_required_fields(request_type=regionalinventory.ListRegionalInventoriesRequest): - transport_class = transports.RegionalInventoryServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_regional_inventories._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_regional_inventories._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", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = regionalinventory.ListRegionalInventoriesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = regionalinventory.ListRegionalInventoriesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_regional_inventories(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_regional_inventories_rest_unset_required_fields(): - transport = transports.RegionalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_regional_inventories._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_regional_inventories_rest_flattened(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = regionalinventory.ListRegionalInventoriesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1/products/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = regionalinventory.ListRegionalInventoriesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.list_regional_inventories(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/inventories/v1beta/{parent=accounts/*/products/*}/regionalInventories" % client.transport._host, args[1]) - - -def test_list_regional_inventories_rest_flattened_error(transport: str = 'rest'): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_regional_inventories( - regionalinventory.ListRegionalInventoriesRequest(), - parent='parent_value', - ) - - -def test_list_regional_inventories_rest_pager(transport: str = 'rest'): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - ], - next_page_token='abc', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[], - next_page_token='def', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - ], - next_page_token='ghi', - ), - regionalinventory.ListRegionalInventoriesResponse( - regional_inventories=[ - regionalinventory.RegionalInventory(), - regionalinventory.RegionalInventory(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(regionalinventory.ListRegionalInventoriesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'accounts/sample1/products/sample2'} - - pager = client.list_regional_inventories(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, regionalinventory.RegionalInventory) - for i in results) - - pages = list(client.list_regional_inventories(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_insert_regional_inventory_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.insert_regional_inventory in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.insert_regional_inventory] = mock_rpc - - request = {} - client.insert_regional_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.insert_regional_inventory(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_insert_regional_inventory_rest_required_fields(request_type=regionalinventory.InsertRegionalInventoryRequest): - transport_class = transports.RegionalInventoryServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).insert_regional_inventory._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).insert_regional_inventory._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = regionalinventory.RegionalInventory() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = regionalinventory.RegionalInventory.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.insert_regional_inventory(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_insert_regional_inventory_rest_unset_required_fields(): - transport = transports.RegionalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.insert_regional_inventory._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "regionalInventory", ))) - - -def test_delete_regional_inventory_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_regional_inventory in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_regional_inventory] = mock_rpc - - request = {} - client.delete_regional_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_regional_inventory(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_delete_regional_inventory_rest_required_fields(request_type=regionalinventory.DeleteRegionalInventoryRequest): - transport_class = transports.RegionalInventoryServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_regional_inventory._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_regional_inventory._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.delete_regional_inventory(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_regional_inventory_rest_unset_required_fields(): - transport = transports.RegionalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_regional_inventory._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_regional_inventory_rest_flattened(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/products/sample2/regionalInventories/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.delete_regional_inventory(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/inventories/v1beta/{name=accounts/*/products/*/regionalInventories/*}" % client.transport._host, args[1]) - - -def test_delete_regional_inventory_rest_flattened_error(transport: str = 'rest'): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_regional_inventory( - regionalinventory.DeleteRegionalInventoryRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.RegionalInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.RegionalInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RegionalInventoryServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.RegionalInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RegionalInventoryServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RegionalInventoryServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.RegionalInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RegionalInventoryServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.RegionalInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = RegionalInventoryServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.RegionalInventoryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.RegionalInventoryServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.RegionalInventoryServiceGrpcTransport, - transports.RegionalInventoryServiceGrpcAsyncIOTransport, - transports.RegionalInventoryServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_kind_grpc(): - transport = RegionalInventoryServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_regional_inventories_empty_call_grpc(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__') as call: - call.return_value = regionalinventory.ListRegionalInventoriesResponse() - client.list_regional_inventories(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regionalinventory.ListRegionalInventoriesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_insert_regional_inventory_empty_call_grpc(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_regional_inventory), - '__call__') as call: - call.return_value = regionalinventory.RegionalInventory() - client.insert_regional_inventory(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regionalinventory.InsertRegionalInventoryRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_regional_inventory_empty_call_grpc(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_regional_inventory), - '__call__') as call: - call.return_value = None - client.delete_regional_inventory(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regionalinventory.DeleteRegionalInventoryRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = RegionalInventoryServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_regional_inventories_empty_call_grpc_asyncio(): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.ListRegionalInventoriesResponse( - next_page_token='next_page_token_value', - )) - await client.list_regional_inventories(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regionalinventory.ListRegionalInventoriesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_insert_regional_inventory_empty_call_grpc_asyncio(): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_regional_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.RegionalInventory( - name='name_value', - account=749, - region='region_value', - availability='availability_value', - )) - await client.insert_regional_inventory(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regionalinventory.InsertRegionalInventoryRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_regional_inventory_empty_call_grpc_asyncio(): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_regional_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_regional_inventory(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regionalinventory.DeleteRegionalInventoryRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = RegionalInventoryServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_list_regional_inventories_rest_bad_request(request_type=regionalinventory.ListRegionalInventoriesRequest): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/products/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_regional_inventories(request) - - -@pytest.mark.parametrize("request_type", [ - regionalinventory.ListRegionalInventoriesRequest, - dict, -]) -def test_list_regional_inventories_rest_call_success(request_type): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/products/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = regionalinventory.ListRegionalInventoriesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = regionalinventory.ListRegionalInventoriesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_regional_inventories(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListRegionalInventoriesPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_regional_inventories_rest_interceptors(null_interceptor): - transport = transports.RegionalInventoryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegionalInventoryServiceRestInterceptor(), - ) - client = RegionalInventoryServiceClient(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.RegionalInventoryServiceRestInterceptor, "post_list_regional_inventories") as post, \ - mock.patch.object(transports.RegionalInventoryServiceRestInterceptor, "post_list_regional_inventories_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.RegionalInventoryServiceRestInterceptor, "pre_list_regional_inventories") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = regionalinventory.ListRegionalInventoriesRequest.pb(regionalinventory.ListRegionalInventoriesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = regionalinventory.ListRegionalInventoriesResponse.to_json(regionalinventory.ListRegionalInventoriesResponse()) - req.return_value.content = return_value - - request = regionalinventory.ListRegionalInventoriesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = regionalinventory.ListRegionalInventoriesResponse() - post_with_metadata.return_value = regionalinventory.ListRegionalInventoriesResponse(), metadata - - client.list_regional_inventories(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_insert_regional_inventory_rest_bad_request(request_type=regionalinventory.InsertRegionalInventoryRequest): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/products/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.insert_regional_inventory(request) - - -@pytest.mark.parametrize("request_type", [ - regionalinventory.InsertRegionalInventoryRequest, - dict, -]) -def test_insert_regional_inventory_rest_call_success(request_type): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/products/sample2'} - request_init["regional_inventory"] = {'name': 'name_value', 'account': 749, 'region': 'region_value', 'price': {'amount_micros': 1408, 'currency_code': 'currency_code_value'}, 'sale_price': {}, 'sale_price_effective_date': {'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}}, 'availability': 'availability_value', 'custom_attributes': [{'name': 'name_value', 'value': 'value_value', 'group_values': {}}]} - # 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 = regionalinventory.InsertRegionalInventoryRequest.meta.fields["regional_inventory"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["regional_inventory"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["regional_inventory"][field])): - del request_init["regional_inventory"][field][i][subfield] - else: - del request_init["regional_inventory"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = regionalinventory.RegionalInventory( - name='name_value', - account=749, - region='region_value', - availability='availability_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = regionalinventory.RegionalInventory.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.insert_regional_inventory(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, regionalinventory.RegionalInventory) - assert response.name == 'name_value' - assert response.account == 749 - assert response.region == 'region_value' - assert response.availability == 'availability_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_insert_regional_inventory_rest_interceptors(null_interceptor): - transport = transports.RegionalInventoryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegionalInventoryServiceRestInterceptor(), - ) - client = RegionalInventoryServiceClient(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.RegionalInventoryServiceRestInterceptor, "post_insert_regional_inventory") as post, \ - mock.patch.object(transports.RegionalInventoryServiceRestInterceptor, "post_insert_regional_inventory_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.RegionalInventoryServiceRestInterceptor, "pre_insert_regional_inventory") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = regionalinventory.InsertRegionalInventoryRequest.pb(regionalinventory.InsertRegionalInventoryRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = regionalinventory.RegionalInventory.to_json(regionalinventory.RegionalInventory()) - req.return_value.content = return_value - - request = regionalinventory.InsertRegionalInventoryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = regionalinventory.RegionalInventory() - post_with_metadata.return_value = regionalinventory.RegionalInventory(), metadata - - client.insert_regional_inventory(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_regional_inventory_rest_bad_request(request_type=regionalinventory.DeleteRegionalInventoryRequest): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/products/sample2/regionalInventories/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_regional_inventory(request) - - -@pytest.mark.parametrize("request_type", [ - regionalinventory.DeleteRegionalInventoryRequest, - dict, -]) -def test_delete_regional_inventory_rest_call_success(request_type): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/products/sample2/regionalInventories/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = '' - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_regional_inventory(request) - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_regional_inventory_rest_interceptors(null_interceptor): - transport = transports.RegionalInventoryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegionalInventoryServiceRestInterceptor(), - ) - client = RegionalInventoryServiceClient(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.RegionalInventoryServiceRestInterceptor, "pre_delete_regional_inventory") as pre: - pre.assert_not_called() - pb_message = regionalinventory.DeleteRegionalInventoryRequest.pb(regionalinventory.DeleteRegionalInventoryRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - request = regionalinventory.DeleteRegionalInventoryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_regional_inventory(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - -def test_initialize_client_w_rest(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_regional_inventories_empty_call_rest(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__') as call: - client.list_regional_inventories(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regionalinventory.ListRegionalInventoriesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_insert_regional_inventory_empty_call_rest(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_regional_inventory), - '__call__') as call: - client.insert_regional_inventory(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regionalinventory.InsertRegionalInventoryRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_regional_inventory_empty_call_rest(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_regional_inventory), - '__call__') as call: - client.delete_regional_inventory(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regionalinventory.DeleteRegionalInventoryRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.RegionalInventoryServiceGrpcTransport, - ) - -def test_regional_inventory_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.RegionalInventoryServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_regional_inventory_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.transports.RegionalInventoryServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.RegionalInventoryServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_regional_inventories', - 'insert_regional_inventory', - 'delete_regional_inventory', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_regional_inventory_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.transports.RegionalInventoryServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RegionalInventoryServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/content', -), - quota_project_id="octopus", - ) - - -def test_regional_inventory_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.shopping.merchant_inventories_v1beta.services.regional_inventory_service.transports.RegionalInventoryServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RegionalInventoryServiceTransport() - adc.assert_called_once() - - -def test_regional_inventory_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - RegionalInventoryServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/content', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.RegionalInventoryServiceGrpcTransport, - transports.RegionalInventoryServiceGrpcAsyncIOTransport, - ], -) -def test_regional_inventory_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/content',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.RegionalInventoryServiceGrpcTransport, - transports.RegionalInventoryServiceGrpcAsyncIOTransport, - transports.RegionalInventoryServiceRestTransport, - ], -) -def test_regional_inventory_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.RegionalInventoryServiceGrpcTransport, grpc_helpers), - (transports.RegionalInventoryServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_regional_inventory_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "merchantapi.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/content', -), - scopes=["1", "2"], - default_host="merchantapi.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.RegionalInventoryServiceGrpcTransport, transports.RegionalInventoryServiceGrpcAsyncIOTransport]) -def test_regional_inventory_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_regional_inventory_service_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.RegionalInventoryServiceRestTransport ( - 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", -]) -def test_regional_inventory_service_host_no_port(transport_name): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='merchantapi.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'merchantapi.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://merchantapi.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_regional_inventory_service_host_with_port(transport_name): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='merchantapi.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'merchantapi.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://merchantapi.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_regional_inventory_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = RegionalInventoryServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = RegionalInventoryServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_regional_inventories._session - session2 = client2.transport.list_regional_inventories._session - assert session1 != session2 - session1 = client1.transport.insert_regional_inventory._session - session2 = client2.transport.insert_regional_inventory._session - assert session1 != session2 - session1 = client1.transport.delete_regional_inventory._session - session2 = client2.transport.delete_regional_inventory._session - assert session1 != session2 -def test_regional_inventory_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RegionalInventoryServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_regional_inventory_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RegionalInventoryServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.RegionalInventoryServiceGrpcTransport, transports.RegionalInventoryServiceGrpcAsyncIOTransport]) -def test_regional_inventory_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.RegionalInventoryServiceGrpcTransport, transports.RegionalInventoryServiceGrpcAsyncIOTransport]) -def test_regional_inventory_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_regional_inventory_path(): - account = "squid" - product = "clam" - region = "whelk" - expected = "accounts/{account}/products/{product}/regionalInventories/{region}".format(account=account, product=product, region=region, ) - actual = RegionalInventoryServiceClient.regional_inventory_path(account, product, region) - assert expected == actual - - -def test_parse_regional_inventory_path(): - expected = { - "account": "octopus", - "product": "oyster", - "region": "nudibranch", - } - path = RegionalInventoryServiceClient.regional_inventory_path(**expected) - - # Check that the path construction is reversible. - actual = RegionalInventoryServiceClient.parse_regional_inventory_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = RegionalInventoryServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = RegionalInventoryServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = RegionalInventoryServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = RegionalInventoryServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = RegionalInventoryServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = RegionalInventoryServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = RegionalInventoryServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = RegionalInventoryServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = RegionalInventoryServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = RegionalInventoryServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = RegionalInventoryServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = RegionalInventoryServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = RegionalInventoryServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = RegionalInventoryServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = RegionalInventoryServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.RegionalInventoryServiceTransport, '_prep_wrapped_messages') as prep: - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.RegionalInventoryServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = RegionalInventoryServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -def test_transport_close_grpc(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -@pytest.mark.asyncio -async def test_transport_close_grpc_asyncio(): - client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close_rest(): - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport), - (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - 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=None, - ) diff --git a/packages/google-shopping-merchant-inventories/docs/index.rst b/packages/google-shopping-merchant-inventories/docs/index.rst index 9c96bf347ccc..17b6ff66a6c6 100644 --- a/packages/google-shopping-merchant-inventories/docs/index.rst +++ b/packages/google-shopping-merchant-inventories/docs/index.rst @@ -2,6 +2,9 @@ .. include:: multiprocessing.rst +This package includes clients for multiple versions of Merchant Inventories API. +By default, you will get version ``merchant_inventories_v1beta``. + API Reference ------------- @@ -11,6 +14,14 @@ API Reference merchant_inventories_v1beta/services_ merchant_inventories_v1beta/types_ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + merchant_inventories_v1/services_ + merchant_inventories_v1/types_ + Changelog --------- diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/merchant_inventories_v1/local_inventory_service.rst b/packages/google-shopping-merchant-inventories/docs/merchant_inventories_v1/local_inventory_service.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/docs/merchant_inventories_v1/local_inventory_service.rst rename to packages/google-shopping-merchant-inventories/docs/merchant_inventories_v1/local_inventory_service.rst diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/merchant_inventories_v1/regional_inventory_service.rst b/packages/google-shopping-merchant-inventories/docs/merchant_inventories_v1/regional_inventory_service.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/docs/merchant_inventories_v1/regional_inventory_service.rst rename to packages/google-shopping-merchant-inventories/docs/merchant_inventories_v1/regional_inventory_service.rst diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/merchant_inventories_v1/services_.rst b/packages/google-shopping-merchant-inventories/docs/merchant_inventories_v1/services_.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/docs/merchant_inventories_v1/services_.rst rename to packages/google-shopping-merchant-inventories/docs/merchant_inventories_v1/services_.rst diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/docs/merchant_inventories_v1/types_.rst b/packages/google-shopping-merchant-inventories/docs/merchant_inventories_v1/types_.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/docs/merchant_inventories_v1/types_.rst rename to packages/google-shopping-merchant-inventories/docs/merchant_inventories_v1/types_.rst diff --git a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories/gapic_version.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories/gapic_version.py index 1f20decfc02d..20a9cd975b02 100644 --- a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories/gapic_version.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.15" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/__init__.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/__init__.py new file mode 100644 index 000000000000..9c5915c48bd9 --- /dev/null +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/__init__.py @@ -0,0 +1,65 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.shopping.merchant_inventories_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.local_inventory_service import ( + LocalInventoryServiceAsyncClient, + LocalInventoryServiceClient, +) +from .services.regional_inventory_service import ( + RegionalInventoryServiceAsyncClient, + RegionalInventoryServiceClient, +) +from .types.inventories_common import ( + LocalInventoryAttributes, + RegionalInventoryAttributes, +) +from .types.localinventory import ( + DeleteLocalInventoryRequest, + InsertLocalInventoryRequest, + ListLocalInventoriesRequest, + ListLocalInventoriesResponse, + LocalInventory, +) +from .types.regionalinventory import ( + DeleteRegionalInventoryRequest, + InsertRegionalInventoryRequest, + ListRegionalInventoriesRequest, + ListRegionalInventoriesResponse, + RegionalInventory, +) + +__all__ = ( + "LocalInventoryServiceAsyncClient", + "RegionalInventoryServiceAsyncClient", + "DeleteLocalInventoryRequest", + "DeleteRegionalInventoryRequest", + "InsertLocalInventoryRequest", + "InsertRegionalInventoryRequest", + "ListLocalInventoriesRequest", + "ListLocalInventoriesResponse", + "ListRegionalInventoriesRequest", + "ListRegionalInventoriesResponse", + "LocalInventory", + "LocalInventoryAttributes", + "LocalInventoryServiceClient", + "RegionalInventory", + "RegionalInventoryAttributes", + "RegionalInventoryServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/gapic_metadata.json b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/gapic_metadata.json similarity index 100% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/gapic_metadata.json rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/gapic_metadata.json diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories/gapic_version.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/gapic_version.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories/gapic_version.py rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/gapic_version.py diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories/py.typed b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/py.typed similarity index 100% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories/py.typed rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/py.typed diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/__init__.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/__init__.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/__init__.py rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/__init__.py diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/__init__.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/__init__.py similarity index 90% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/__init__.py rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/__init__.py index 4b805a80aace..1dc4eb050109 100644 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/__init__.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import LocalInventoryServiceClient from .async_client import LocalInventoryServiceAsyncClient +from .client import LocalInventoryServiceClient __all__ = ( - 'LocalInventoryServiceClient', - 'LocalInventoryServiceAsyncClient', + "LocalInventoryServiceClient", + "LocalInventoryServiceAsyncClient", ) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/async_client.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/async_client.py similarity index 80% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/async_client.py rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/async_client.py index 11fb9a200efe..77f8e3838991 100644 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/async_client.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/async_client.py @@ -13,42 +13,59 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import logging as std_logging from collections import OrderedDict +import logging as std_logging import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.shopping.merchant_inventories_v1 import gapic_version as package_version +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) -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.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf +from google.shopping.merchant_inventories_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore -from google.shopping.merchant_inventories_v1.services.local_inventory_service import pagers -from google.shopping.merchant_inventories_v1.types import inventories_common -from google.shopping.merchant_inventories_v1.types import localinventory -from .transports.base import LocalInventoryServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import LocalInventoryServiceGrpcAsyncIOTransport +from google.shopping.merchant_inventories_v1.services.local_inventory_service import ( + pagers, +) +from google.shopping.merchant_inventories_v1.types import ( + inventories_common, + localinventory, +) + from .client import LocalInventoryServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, LocalInventoryServiceTransport +from .transports.grpc_asyncio import LocalInventoryServiceGrpcAsyncIOTransport 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 LocalInventoryServiceAsyncClient: """Service to manage local inventory for products""" @@ -61,18 +78,38 @@ class LocalInventoryServiceAsyncClient: _DEFAULT_ENDPOINT_TEMPLATE = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE _DEFAULT_UNIVERSE = LocalInventoryServiceClient._DEFAULT_UNIVERSE - local_inventory_path = staticmethod(LocalInventoryServiceClient.local_inventory_path) - parse_local_inventory_path = staticmethod(LocalInventoryServiceClient.parse_local_inventory_path) - common_billing_account_path = staticmethod(LocalInventoryServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(LocalInventoryServiceClient.parse_common_billing_account_path) + local_inventory_path = staticmethod( + LocalInventoryServiceClient.local_inventory_path + ) + parse_local_inventory_path = staticmethod( + LocalInventoryServiceClient.parse_local_inventory_path + ) + common_billing_account_path = staticmethod( + LocalInventoryServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + LocalInventoryServiceClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(LocalInventoryServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(LocalInventoryServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(LocalInventoryServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(LocalInventoryServiceClient.parse_common_organization_path) + parse_common_folder_path = staticmethod( + LocalInventoryServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + LocalInventoryServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + LocalInventoryServiceClient.parse_common_organization_path + ) common_project_path = staticmethod(LocalInventoryServiceClient.common_project_path) - parse_common_project_path = staticmethod(LocalInventoryServiceClient.parse_common_project_path) - common_location_path = staticmethod(LocalInventoryServiceClient.common_location_path) - parse_common_location_path = staticmethod(LocalInventoryServiceClient.parse_common_location_path) + parse_common_project_path = staticmethod( + LocalInventoryServiceClient.parse_common_project_path + ) + common_location_path = staticmethod( + LocalInventoryServiceClient.common_location_path + ) + parse_common_location_path = staticmethod( + LocalInventoryServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -108,7 +145,9 @@ 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: @@ -171,12 +210,20 @@ def universe_domain(self) -> str: get_transport_class = LocalInventoryServiceClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, LocalInventoryServiceTransport, Callable[..., LocalInventoryServiceTransport]]] = "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, + LocalInventoryServiceTransport, + Callable[..., LocalInventoryServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the local inventory service async client. Args: @@ -231,31 +278,41 @@ 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.shopping.merchant.inventories_v1.LocalInventoryServiceAsyncClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.inventories.v1.LocalInventoryService", - "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.shopping.merchant.inventories.v1.LocalInventoryService", "credentialsType": None, - } + }, ) - async def list_local_inventories(self, - request: Optional[Union[localinventory.ListLocalInventoriesRequest, 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.ListLocalInventoriesAsyncPager: + async def list_local_inventories( + self, + request: Optional[ + Union[localinventory.ListLocalInventoriesRequest, 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.ListLocalInventoriesAsyncPager: r"""Lists the ``LocalInventory`` resources for the given product in your merchant account. The response might contain fewer items than specified by ``pageSize``. If ``pageToken`` was returned in @@ -322,10 +379,14 @@ async def sample_list_local_inventories(): # - 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. @@ -339,14 +400,14 @@ async def sample_list_local_inventories(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_local_inventories] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_local_inventories + ] # 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. @@ -374,13 +435,16 @@ async def sample_list_local_inventories(): # Done; return the response. return response - async def insert_local_inventory(self, - request: Optional[Union[localinventory.InsertLocalInventoryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> localinventory.LocalInventory: + async def insert_local_inventory( + self, + request: Optional[ + Union[localinventory.InsertLocalInventoryRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> localinventory.LocalInventory: r"""Inserts a ``LocalInventory`` resource to a product in your merchant account. @@ -451,14 +515,14 @@ async def sample_insert_local_inventory(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.insert_local_inventory] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.insert_local_inventory + ] # 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. @@ -475,14 +539,17 @@ async def sample_insert_local_inventory(): # Done; return the response. return response - async def delete_local_inventory(self, - request: Optional[Union[localinventory.DeleteLocalInventoryRequest, dict]] = None, - *, - name: 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_local_inventory( + self, + request: Optional[ + Union[localinventory.DeleteLocalInventoryRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes the specified ``LocalInventory`` from the given product in your merchant account. It might take a up to an hour for the ``LocalInventory`` to be deleted from the specific product. Once @@ -535,10 +602,14 @@ async def sample_delete_local_inventory(): # - 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. @@ -552,14 +623,14 @@ async def sample_delete_local_inventory(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_local_inventory] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_local_inventory + ] # 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. @@ -579,12 +650,13 @@ async def __aenter__(self) -> "LocalInventoryServiceAsyncClient": 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__ = ( - "LocalInventoryServiceAsyncClient", -) +__all__ = ("LocalInventoryServiceAsyncClient",) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/client.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/client.py similarity index 79% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/client.py rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/client.py index 716a5957f744..b886c441d982 100644 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/client.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/client.py @@ -19,22 +19,34 @@ import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) import warnings -from google.shopping.merchant_inventories_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.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf +from google.shopping.merchant_inventories_v1 import gapic_version as package_version + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -42,16 +54,22 @@ 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.shopping.merchant_inventories_v1.services.local_inventory_service import pagers -from google.shopping.merchant_inventories_v1.types import inventories_common -from google.shopping.merchant_inventories_v1.types import localinventory -from .transports.base import LocalInventoryServiceTransport, DEFAULT_CLIENT_INFO +from google.shopping.merchant_inventories_v1.services.local_inventory_service import ( + pagers, +) +from google.shopping.merchant_inventories_v1.types import ( + inventories_common, + localinventory, +) + +from .transports.base import DEFAULT_CLIENT_INFO, LocalInventoryServiceTransport from .transports.grpc import LocalInventoryServiceGrpcTransport from .transports.grpc_asyncio import LocalInventoryServiceGrpcAsyncIOTransport from .transports.rest import LocalInventoryServiceRestTransport @@ -64,14 +82,18 @@ class LocalInventoryServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[LocalInventoryServiceTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[LocalInventoryServiceTransport]] _transport_registry["grpc"] = LocalInventoryServiceGrpcTransport _transport_registry["grpc_asyncio"] = LocalInventoryServiceGrpcAsyncIOTransport _transport_registry["rest"] = LocalInventoryServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[LocalInventoryServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[LocalInventoryServiceTransport]: """Returns an appropriate transport class. Args: @@ -163,8 +185,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: LocalInventoryServiceClient: 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) @@ -181,73 +202,108 @@ def transport(self) -> LocalInventoryServiceTransport: return self._transport @staticmethod - def local_inventory_path(account: str,product: str,store_code: str,) -> str: + def local_inventory_path( + account: str, + product: str, + store_code: str, + ) -> str: """Returns a fully-qualified local_inventory string.""" - return "accounts/{account}/products/{product}/localInventories/{store_code}".format(account=account, product=product, store_code=store_code, ) + return "accounts/{account}/products/{product}/localInventories/{store_code}".format( + account=account, + product=product, + store_code=store_code, + ) @staticmethod - def parse_local_inventory_path(path: str) -> Dict[str,str]: + def parse_local_inventory_path(path: str) -> Dict[str, str]: """Parses a local_inventory path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/products/(?P.+?)/localInventories/(?P.+?)$", path) + m = re.match( + r"^accounts/(?P.+?)/products/(?P.+?)/localInventories/(?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: @@ -279,16 +335,22 @@ 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 = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) 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 @@ -301,7 +363,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 @@ -322,13 +386,19 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) 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 == "true", use_mtls_endpoint, universe_domain_env @staticmethod @@ -351,7 +421,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: @@ -367,17 +439,27 @@ 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 = LocalInventoryServiceClient._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 = LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = ( + LocalInventoryServiceClient._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: @@ -413,15 +495,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 @@ -454,12 +539,20 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, LocalInventoryServiceTransport, Callable[..., LocalInventoryServiceTransport]]] = 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, + LocalInventoryServiceTransport, + Callable[..., LocalInventoryServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the local inventory service client. Args: @@ -514,14 +607,24 @@ 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 = LocalInventoryServiceClient._read_environment_variables() - self._client_cert_source = LocalInventoryServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = LocalInventoryServiceClient._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, + ) = LocalInventoryServiceClient._read_environment_variables() + self._client_cert_source = LocalInventoryServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = LocalInventoryServiceClient._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 @@ -532,7 +635,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 @@ -541,8 +646,10 @@ def __init__(self, *, if transport_provided: # transport is a LocalInventoryServiceTransport 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 " @@ -551,20 +658,30 @@ def __init__(self, *, self._transport = cast(LocalInventoryServiceTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - LocalInventoryServiceClient._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or LocalInventoryServiceClient._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[LocalInventoryServiceTransport], Callable[..., LocalInventoryServiceTransport]] = ( + transport_init: Union[ + Type[LocalInventoryServiceTransport], + Callable[..., LocalInventoryServiceTransport], + ] = ( LocalInventoryServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., LocalInventoryServiceTransport], transport) @@ -583,28 +700,39 @@ 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.shopping.merchant.inventories_v1.LocalInventoryServiceClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.inventories.v1.LocalInventoryService", - "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.shopping.merchant.inventories.v1.LocalInventoryService", "credentialsType": None, - } + }, ) - def list_local_inventories(self, - request: Optional[Union[localinventory.ListLocalInventoriesRequest, 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.ListLocalInventoriesPager: + def list_local_inventories( + self, + request: Optional[ + Union[localinventory.ListLocalInventoriesRequest, 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.ListLocalInventoriesPager: r"""Lists the ``LocalInventory`` resources for the given product in your merchant account. The response might contain fewer items than specified by ``pageSize``. If ``pageToken`` was returned in @@ -671,10 +799,14 @@ def sample_list_local_inventories(): # - 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. @@ -692,9 +824,7 @@ def sample_list_local_inventories(): # 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. @@ -722,13 +852,16 @@ def sample_list_local_inventories(): # Done; return the response. return response - def insert_local_inventory(self, - request: Optional[Union[localinventory.InsertLocalInventoryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> localinventory.LocalInventory: + def insert_local_inventory( + self, + request: Optional[ + Union[localinventory.InsertLocalInventoryRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> localinventory.LocalInventory: r"""Inserts a ``LocalInventory`` resource to a product in your merchant account. @@ -804,9 +937,7 @@ def sample_insert_local_inventory(): # 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. @@ -823,14 +954,17 @@ def sample_insert_local_inventory(): # Done; return the response. return response - def delete_local_inventory(self, - request: Optional[Union[localinventory.DeleteLocalInventoryRequest, dict]] = None, - *, - name: 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_local_inventory( + self, + request: Optional[ + Union[localinventory.DeleteLocalInventoryRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes the specified ``LocalInventory`` from the given product in your merchant account. It might take a up to an hour for the ``LocalInventory`` to be deleted from the specific product. Once @@ -883,10 +1017,14 @@ def sample_delete_local_inventory(): # - 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. @@ -904,9 +1042,7 @@ def sample_delete_local_inventory(): # 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. @@ -934,16 +1070,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__ = ( - "LocalInventoryServiceClient", -) +__all__ = ("LocalInventoryServiceClient",) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/pagers.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/pagers.py similarity index 79% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/pagers.py rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/pagers.py index b25fe0ffc20f..2f3ceac7c22a 100644 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/pagers.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/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 ListLocalInventoriesPager: 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[..., localinventory.ListLocalInventoriesResponse], - request: localinventory.ListLocalInventoriesRequest, - response: localinventory.ListLocalInventoriesResponse, - *, - 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[..., localinventory.ListLocalInventoriesResponse], + request: localinventory.ListLocalInventoriesRequest, + response: localinventory.ListLocalInventoriesResponse, + *, + 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[localinventory.ListLocalInventoriesResponse]: 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[localinventory.LocalInventory]: @@ -92,7 +114,7 @@ def __iter__(self) -> Iterator[localinventory.LocalInventory]: yield from page.local_inventories 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 ListLocalInventoriesAsyncPager: @@ -112,14 +134,17 @@ class ListLocalInventoriesAsyncPager: 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[localinventory.ListLocalInventoriesResponse]], - request: localinventory.ListLocalInventoriesRequest, - response: localinventory.ListLocalInventoriesResponse, - *, - 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[localinventory.ListLocalInventoriesResponse]], + request: localinventory.ListLocalInventoriesRequest, + response: localinventory.ListLocalInventoriesResponse, + *, + 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: @@ -152,8 +177,14 @@ async def pages(self) -> AsyncIterator[localinventory.ListLocalInventoriesRespon 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[localinventory.LocalInventory]: async def async_generator(): async for page in self.pages: @@ -163,4 +194,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/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/README.rst b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/README.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/README.rst rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/README.rst diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/__init__.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/__init__.py similarity index 59% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/__init__.py rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/__init__.py index e1c84f7bce12..b6d364c844b2 100644 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/__init__.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/__init__.py @@ -19,20 +19,23 @@ from .base import LocalInventoryServiceTransport from .grpc import LocalInventoryServiceGrpcTransport from .grpc_asyncio import LocalInventoryServiceGrpcAsyncIOTransport -from .rest import LocalInventoryServiceRestTransport -from .rest import LocalInventoryServiceRestInterceptor - +from .rest import ( + LocalInventoryServiceRestInterceptor, + LocalInventoryServiceRestTransport, +) # Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[LocalInventoryServiceTransport]] -_transport_registry['grpc'] = LocalInventoryServiceGrpcTransport -_transport_registry['grpc_asyncio'] = LocalInventoryServiceGrpcAsyncIOTransport -_transport_registry['rest'] = LocalInventoryServiceRestTransport +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[LocalInventoryServiceTransport]] +_transport_registry["grpc"] = LocalInventoryServiceGrpcTransport +_transport_registry["grpc_asyncio"] = LocalInventoryServiceGrpcAsyncIOTransport +_transport_registry["rest"] = LocalInventoryServiceRestTransport __all__ = ( - 'LocalInventoryServiceTransport', - 'LocalInventoryServiceGrpcTransport', - 'LocalInventoryServiceGrpcAsyncIOTransport', - 'LocalInventoryServiceRestTransport', - 'LocalInventoryServiceRestInterceptor', + "LocalInventoryServiceTransport", + "LocalInventoryServiceGrpcTransport", + "LocalInventoryServiceGrpcAsyncIOTransport", + "LocalInventoryServiceRestTransport", + "LocalInventoryServiceRestInterceptor", ) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/base.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/base.py similarity index 67% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/base.py rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/base.py index abbcbaee2cb8..7ff5ea79c760 100644 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/base.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/base.py @@ -16,21 +16,22 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.shopping.merchant_inventories_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 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.protobuf import empty_pb2 # type: ignore + +from google.shopping.merchant_inventories_v1 import gapic_version as package_version from google.shopping.merchant_inventories_v1.types import localinventory -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 +40,23 @@ class LocalInventoryServiceTransport(abc.ABC): """Abstract transport class for LocalInventoryService.""" - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/content', - ) + AUTH_SCOPES = ("https://www.googleapis.com/auth/content",) - DEFAULT_HOST: str = 'merchantapi.googleapis.com' + DEFAULT_HOST: str = "merchantapi.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: @@ -92,30 +92,38 @@ 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_kwargs, quota_project_id=quota_project_id + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + 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,42 +148,45 @@ 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() @property - def list_local_inventories(self) -> Callable[ - [localinventory.ListLocalInventoriesRequest], - Union[ - localinventory.ListLocalInventoriesResponse, - Awaitable[localinventory.ListLocalInventoriesResponse] - ]]: + def list_local_inventories( + self, + ) -> Callable[ + [localinventory.ListLocalInventoriesRequest], + Union[ + localinventory.ListLocalInventoriesResponse, + Awaitable[localinventory.ListLocalInventoriesResponse], + ], + ]: raise NotImplementedError() @property - def insert_local_inventory(self) -> Callable[ - [localinventory.InsertLocalInventoryRequest], - Union[ - localinventory.LocalInventory, - Awaitable[localinventory.LocalInventory] - ]]: + def insert_local_inventory( + self, + ) -> Callable[ + [localinventory.InsertLocalInventoryRequest], + Union[localinventory.LocalInventory, Awaitable[localinventory.LocalInventory]], + ]: raise NotImplementedError() @property - def delete_local_inventory(self) -> Callable[ - [localinventory.DeleteLocalInventoryRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_local_inventory( + self, + ) -> Callable[ + [localinventory.DeleteLocalInventoryRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property @@ -183,6 +194,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'LocalInventoryServiceTransport', -) +__all__ = ("LocalInventoryServiceTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/grpc.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/grpc.py similarity index 84% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/grpc.py rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/grpc.py index f08af2b10a00..c6605301b54f 100644 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/grpc.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/grpc.py @@ -16,26 +16,26 @@ import json import logging as std_logging import pickle -import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # 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 from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf import empty_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message - import grpc # type: ignore import proto # type: ignore -from google.protobuf import empty_pb2 # type: ignore from google.shopping.merchant_inventories_v1.types import localinventory -from .base import LocalInventoryServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, LocalInventoryServiceTransport 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,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): @@ -66,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.shopping.merchant.inventories.v1.LocalInventoryService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -77,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) @@ -92,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.shopping.merchant.inventories.v1.LocalInventoryService", "rpcName": client_call_details.method, "response": grpc_response, @@ -114,23 +120,26 @@ class LocalInventoryServiceGrpcTransport(LocalInventoryServiceTransport): 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 = 'merchantapi.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 = "merchantapi.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: @@ -252,19 +261,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 = 'merchantapi.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 = "merchantapi.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. @@ -299,19 +312,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 list_local_inventories(self) -> Callable[ - [localinventory.ListLocalInventoriesRequest], - localinventory.ListLocalInventoriesResponse]: + def list_local_inventories( + self, + ) -> Callable[ + [localinventory.ListLocalInventoriesRequest], + localinventory.ListLocalInventoriesResponse, + ]: r"""Return a callable for the list local inventories method over gRPC. Lists the ``LocalInventory`` resources for the given product in @@ -332,18 +347,20 @@ def list_local_inventories(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_local_inventories' not in self._stubs: - self._stubs['list_local_inventories'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1.LocalInventoryService/ListLocalInventories', + if "list_local_inventories" not in self._stubs: + self._stubs["list_local_inventories"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.inventories.v1.LocalInventoryService/ListLocalInventories", request_serializer=localinventory.ListLocalInventoriesRequest.serialize, response_deserializer=localinventory.ListLocalInventoriesResponse.deserialize, ) - return self._stubs['list_local_inventories'] + return self._stubs["list_local_inventories"] @property - def insert_local_inventory(self) -> Callable[ - [localinventory.InsertLocalInventoryRequest], - localinventory.LocalInventory]: + def insert_local_inventory( + self, + ) -> Callable[ + [localinventory.InsertLocalInventoryRequest], localinventory.LocalInventory + ]: r"""Return a callable for the insert local inventory method over gRPC. Inserts a ``LocalInventory`` resource to a product in your @@ -367,18 +384,18 @@ def insert_local_inventory(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'insert_local_inventory' not in self._stubs: - self._stubs['insert_local_inventory'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1.LocalInventoryService/InsertLocalInventory', + if "insert_local_inventory" not in self._stubs: + self._stubs["insert_local_inventory"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.inventories.v1.LocalInventoryService/InsertLocalInventory", request_serializer=localinventory.InsertLocalInventoryRequest.serialize, response_deserializer=localinventory.LocalInventory.deserialize, ) - return self._stubs['insert_local_inventory'] + return self._stubs["insert_local_inventory"] @property - def delete_local_inventory(self) -> Callable[ - [localinventory.DeleteLocalInventoryRequest], - empty_pb2.Empty]: + def delete_local_inventory( + self, + ) -> Callable[[localinventory.DeleteLocalInventoryRequest], empty_pb2.Empty]: r"""Return a callable for the delete local inventory method over gRPC. Deletes the specified ``LocalInventory`` from the given product @@ -397,13 +414,13 @@ def delete_local_inventory(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_local_inventory' not in self._stubs: - self._stubs['delete_local_inventory'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1.LocalInventoryService/DeleteLocalInventory', + if "delete_local_inventory" not in self._stubs: + self._stubs["delete_local_inventory"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.inventories.v1.LocalInventoryService/DeleteLocalInventory", request_serializer=localinventory.DeleteLocalInventoryRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_local_inventory'] + return self._stubs["delete_local_inventory"] def close(self): self._logged_channel.close() @@ -413,6 +430,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'LocalInventoryServiceGrpcTransport', -) +__all__ = ("LocalInventoryServiceGrpcTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/grpc_asyncio.py similarity index 83% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/grpc_asyncio.py rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/grpc_asyncio.py index ab7e499ed9db..147818d38d7e 100644 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/grpc_asyncio.py @@ -15,31 +15,31 @@ # import inspect import json -import pickle import logging as std_logging -import warnings +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings -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 import empty_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore +import grpc # type: ignore from grpc.experimental import aio # type: ignore +import proto # type: ignore -from google.protobuf import empty_pb2 # type: ignore from google.shopping.merchant_inventories_v1.types import localinventory -from .base import LocalInventoryServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, LocalInventoryServiceTransport from .grpc import LocalInventoryServiceGrpcTransport 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,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): @@ -70,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.shopping.merchant.inventories.v1.LocalInventoryService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -81,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) @@ -96,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.shopping.merchant.inventories.v1.LocalInventoryService", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -123,13 +131,15 @@ class LocalInventoryServiceGrpcAsyncIOTransport(LocalInventoryServiceTransport): _stubs: Dict[str, Callable] = {} @classmethod - def create_channel(cls, - host: str = 'merchantapi.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 = "merchantapi.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. @@ -159,24 +169,26 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) - def __init__(self, *, - host: str = 'merchantapi.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 = "merchantapi.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: @@ -300,7 +312,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) @@ -315,9 +329,12 @@ def grpc_channel(self) -> aio.Channel: return self._grpc_channel @property - def list_local_inventories(self) -> Callable[ - [localinventory.ListLocalInventoriesRequest], - Awaitable[localinventory.ListLocalInventoriesResponse]]: + def list_local_inventories( + self, + ) -> Callable[ + [localinventory.ListLocalInventoriesRequest], + Awaitable[localinventory.ListLocalInventoriesResponse], + ]: r"""Return a callable for the list local inventories method over gRPC. Lists the ``LocalInventory`` resources for the given product in @@ -338,18 +355,21 @@ def list_local_inventories(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_local_inventories' not in self._stubs: - self._stubs['list_local_inventories'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1.LocalInventoryService/ListLocalInventories', + if "list_local_inventories" not in self._stubs: + self._stubs["list_local_inventories"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.inventories.v1.LocalInventoryService/ListLocalInventories", request_serializer=localinventory.ListLocalInventoriesRequest.serialize, response_deserializer=localinventory.ListLocalInventoriesResponse.deserialize, ) - return self._stubs['list_local_inventories'] + return self._stubs["list_local_inventories"] @property - def insert_local_inventory(self) -> Callable[ - [localinventory.InsertLocalInventoryRequest], - Awaitable[localinventory.LocalInventory]]: + def insert_local_inventory( + self, + ) -> Callable[ + [localinventory.InsertLocalInventoryRequest], + Awaitable[localinventory.LocalInventory], + ]: r"""Return a callable for the insert local inventory method over gRPC. Inserts a ``LocalInventory`` resource to a product in your @@ -373,18 +393,20 @@ def insert_local_inventory(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'insert_local_inventory' not in self._stubs: - self._stubs['insert_local_inventory'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1.LocalInventoryService/InsertLocalInventory', + if "insert_local_inventory" not in self._stubs: + self._stubs["insert_local_inventory"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.inventories.v1.LocalInventoryService/InsertLocalInventory", request_serializer=localinventory.InsertLocalInventoryRequest.serialize, response_deserializer=localinventory.LocalInventory.deserialize, ) - return self._stubs['insert_local_inventory'] + return self._stubs["insert_local_inventory"] @property - def delete_local_inventory(self) -> Callable[ - [localinventory.DeleteLocalInventoryRequest], - Awaitable[empty_pb2.Empty]]: + def delete_local_inventory( + self, + ) -> Callable[ + [localinventory.DeleteLocalInventoryRequest], Awaitable[empty_pb2.Empty] + ]: r"""Return a callable for the delete local inventory method over gRPC. Deletes the specified ``LocalInventory`` from the given product @@ -403,16 +425,16 @@ def delete_local_inventory(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_local_inventory' not in self._stubs: - self._stubs['delete_local_inventory'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1.LocalInventoryService/DeleteLocalInventory', + if "delete_local_inventory" not in self._stubs: + self._stubs["delete_local_inventory"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.inventories.v1.LocalInventoryService/DeleteLocalInventory", request_serializer=localinventory.DeleteLocalInventoryRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_local_inventory'] + return self._stubs["delete_local_inventory"] 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.list_local_inventories: self._wrap_method( self.list_local_inventories, @@ -444,6 +466,4 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ( - 'LocalInventoryServiceGrpcAsyncIOTransport', -) +__all__ = ("LocalInventoryServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/rest.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/rest.py similarity index 69% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/rest.py rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/rest.py index 70abbea6e70c..b5ffb7459b00 100644 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/rest.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/rest.py @@ -13,32 +13,26 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import logging +import dataclasses import json # type: ignore +import logging +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings -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.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import gapic_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore import google.protobuf - +from google.protobuf import empty_pb2 # type: ignore from google.protobuf import json_format - from requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -from google.protobuf import empty_pb2 # type: ignore from google.shopping.merchant_inventories_v1.types import localinventory - -from .rest_base import _BaseLocalInventoryServiceRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseLocalInventoryServiceRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -47,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 @@ -103,7 +98,15 @@ def post_list_local_inventories(self, response): """ - def pre_delete_local_inventory(self, request: localinventory.DeleteLocalInventoryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[localinventory.DeleteLocalInventoryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_delete_local_inventory( + self, + request: localinventory.DeleteLocalInventoryRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + localinventory.DeleteLocalInventoryRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for delete_local_inventory Override in a subclass to manipulate the request or metadata @@ -111,7 +114,14 @@ def pre_delete_local_inventory(self, request: localinventory.DeleteLocalInventor """ return request, metadata - def pre_insert_local_inventory(self, request: localinventory.InsertLocalInventoryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[localinventory.InsertLocalInventoryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_insert_local_inventory( + self, + request: localinventory.InsertLocalInventoryRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + localinventory.InsertLocalInventoryRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for insert_local_inventory Override in a subclass to manipulate the request or metadata @@ -119,7 +129,9 @@ def pre_insert_local_inventory(self, request: localinventory.InsertLocalInventor """ return request, metadata - def post_insert_local_inventory(self, response: localinventory.LocalInventory) -> localinventory.LocalInventory: + def post_insert_local_inventory( + self, response: localinventory.LocalInventory + ) -> localinventory.LocalInventory: """Post-rpc interceptor for insert_local_inventory DEPRECATED. Please use the `post_insert_local_inventory_with_metadata` @@ -132,7 +144,11 @@ def post_insert_local_inventory(self, response: localinventory.LocalInventory) - """ return response - def post_insert_local_inventory_with_metadata(self, response: localinventory.LocalInventory, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[localinventory.LocalInventory, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_insert_local_inventory_with_metadata( + self, + response: localinventory.LocalInventory, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[localinventory.LocalInventory, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for insert_local_inventory Override in a subclass to read or manipulate the response or metadata after it @@ -147,7 +163,14 @@ def post_insert_local_inventory_with_metadata(self, response: localinventory.Loc """ return response, metadata - def pre_list_local_inventories(self, request: localinventory.ListLocalInventoriesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[localinventory.ListLocalInventoriesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_local_inventories( + self, + request: localinventory.ListLocalInventoriesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + localinventory.ListLocalInventoriesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for list_local_inventories Override in a subclass to manipulate the request or metadata @@ -155,7 +178,9 @@ def pre_list_local_inventories(self, request: localinventory.ListLocalInventorie """ return request, metadata - def post_list_local_inventories(self, response: localinventory.ListLocalInventoriesResponse) -> localinventory.ListLocalInventoriesResponse: + def post_list_local_inventories( + self, response: localinventory.ListLocalInventoriesResponse + ) -> localinventory.ListLocalInventoriesResponse: """Post-rpc interceptor for list_local_inventories DEPRECATED. Please use the `post_list_local_inventories_with_metadata` @@ -168,7 +193,14 @@ def post_list_local_inventories(self, response: localinventory.ListLocalInventor """ return response - def post_list_local_inventories_with_metadata(self, response: localinventory.ListLocalInventoriesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[localinventory.ListLocalInventoriesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_local_inventories_with_metadata( + self, + response: localinventory.ListLocalInventoriesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + localinventory.ListLocalInventoriesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for list_local_inventories Override in a subclass to read or manipulate the response or metadata after it @@ -203,20 +235,21 @@ class LocalInventoryServiceRestTransport(_BaseLocalInventoryServiceRestTransport It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__(self, *, - host: str = 'merchantapi.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[LocalInventoryServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "merchantapi.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[LocalInventoryServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -259,16 +292,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 LocalInventoryServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _DeleteLocalInventory(_BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory, LocalInventoryServiceRestStub): + class _DeleteLocalInventory( + _BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory, + LocalInventoryServiceRestStub, + ): def __hash__(self): return hash("LocalInventoryServiceRestTransport.DeleteLocalInventory") @@ -280,26 +317,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: localinventory.DeleteLocalInventoryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): + def __call__( + self, + request: localinventory.DeleteLocalInventoryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): r"""Call the delete local inventory method over HTTP. Args: @@ -314,30 +353,42 @@ def __call__(self, be of type `bytes`. """ - http_options = _BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._get_http_options() + http_options = ( + _BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._get_http_options() + ) - request, metadata = self._interceptor.pre_delete_local_inventory(request, metadata) - transcoded_request = _BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_delete_local_inventory( + request, metadata + ) + transcoded_request = _BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.shopping.merchant.inventories_v1.LocalInventoryServiceClient.DeleteLocalInventory", - extra = { + extra={ "serviceName": "google.shopping.merchant.inventories.v1.LocalInventoryService", "rpcName": "DeleteLocalInventory", "httpRequest": http_request, @@ -346,14 +397,26 @@ def __call__(self, ) # Send the request - response = LocalInventoryServiceRestTransport._DeleteLocalInventory._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = ( + LocalInventoryServiceRestTransport._DeleteLocalInventory._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 _InsertLocalInventory(_BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory, LocalInventoryServiceRestStub): + class _InsertLocalInventory( + _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory, + LocalInventoryServiceRestStub, + ): def __hash__(self): return hash("LocalInventoryServiceRestTransport.InsertLocalInventory") @@ -365,27 +428,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: localinventory.InsertLocalInventoryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> localinventory.LocalInventory: + def __call__( + self, + request: localinventory.InsertLocalInventoryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> localinventory.LocalInventory: r"""Call the insert local inventory method over HTTP. Args: @@ -411,32 +476,46 @@ def __call__(self, """ - http_options = _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_http_options() + http_options = ( + _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_http_options() + ) - request, metadata = self._interceptor.pre_insert_local_inventory(request, metadata) - transcoded_request = _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_insert_local_inventory( + request, metadata + ) + transcoded_request = _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_transcoded_request( + http_options, request + ) - body = _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_request_body_json(transcoded_request) + body = _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.shopping.merchant.inventories_v1.LocalInventoryServiceClient.InsertLocalInventory", - extra = { + extra={ "serviceName": "google.shopping.merchant.inventories.v1.LocalInventoryService", "rpcName": "InsertLocalInventory", "httpRequest": http_request, @@ -445,7 +524,17 @@ def __call__(self, ) # Send the request - response = LocalInventoryServiceRestTransport._InsertLocalInventory._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = ( + LocalInventoryServiceRestTransport._InsertLocalInventory._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. @@ -460,20 +549,24 @@ def __call__(self, resp = self._interceptor.post_insert_local_inventory(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_insert_local_inventory_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_insert_local_inventory_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = localinventory.LocalInventory.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.shopping.merchant.inventories_v1.LocalInventoryServiceClient.insert_local_inventory", - extra = { + extra={ "serviceName": "google.shopping.merchant.inventories.v1.LocalInventoryService", "rpcName": "InsertLocalInventory", "metadata": http_response["headers"], @@ -482,7 +575,10 @@ def __call__(self, ) return resp - class _ListLocalInventories(_BaseLocalInventoryServiceRestTransport._BaseListLocalInventories, LocalInventoryServiceRestStub): + class _ListLocalInventories( + _BaseLocalInventoryServiceRestTransport._BaseListLocalInventories, + LocalInventoryServiceRestStub, + ): def __hash__(self): return hash("LocalInventoryServiceRestTransport.ListLocalInventories") @@ -494,26 +590,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: localinventory.ListLocalInventoriesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> localinventory.ListLocalInventoriesResponse: + def __call__( + self, + request: localinventory.ListLocalInventoriesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> localinventory.ListLocalInventoriesResponse: r"""Call the list local inventories method over HTTP. Args: @@ -534,30 +632,42 @@ def __call__(self, """ - http_options = _BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._get_http_options() + http_options = ( + _BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._get_http_options() + ) - request, metadata = self._interceptor.pre_list_local_inventories(request, metadata) - transcoded_request = _BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_list_local_inventories( + request, metadata + ) + transcoded_request = _BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.shopping.merchant.inventories_v1.LocalInventoryServiceClient.ListLocalInventories", - extra = { + extra={ "serviceName": "google.shopping.merchant.inventories.v1.LocalInventoryService", "rpcName": "ListLocalInventories", "httpRequest": http_request, @@ -566,7 +676,16 @@ def __call__(self, ) # Send the request - response = LocalInventoryServiceRestTransport._ListLocalInventories._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = ( + LocalInventoryServiceRestTransport._ListLocalInventories._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -581,20 +700,26 @@ def __call__(self, resp = self._interceptor.post_list_local_inventories(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_local_inventories_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_local_inventories_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = localinventory.ListLocalInventoriesResponse.to_json(response) + response_payload = ( + localinventory.ListLocalInventoriesResponse.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.shopping.merchant.inventories_v1.LocalInventoryServiceClient.list_local_inventories", - extra = { + extra={ "serviceName": "google.shopping.merchant.inventories.v1.LocalInventoryService", "rpcName": "ListLocalInventories", "metadata": http_response["headers"], @@ -604,28 +729,33 @@ def __call__(self, return resp @property - def delete_local_inventory(self) -> Callable[ - [localinventory.DeleteLocalInventoryRequest], - empty_pb2.Empty]: + def delete_local_inventory( + self, + ) -> Callable[[localinventory.DeleteLocalInventoryRequest], 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._DeleteLocalInventory(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteLocalInventory(self._session, self._host, self._interceptor) # type: ignore @property - def insert_local_inventory(self) -> Callable[ - [localinventory.InsertLocalInventoryRequest], - localinventory.LocalInventory]: + def insert_local_inventory( + self, + ) -> Callable[ + [localinventory.InsertLocalInventoryRequest], localinventory.LocalInventory + ]: # 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._InsertLocalInventory(self._session, self._host, self._interceptor) # type: ignore + return self._InsertLocalInventory(self._session, self._host, self._interceptor) # type: ignore @property - def list_local_inventories(self) -> Callable[ - [localinventory.ListLocalInventoriesRequest], - localinventory.ListLocalInventoriesResponse]: + def list_local_inventories( + self, + ) -> Callable[ + [localinventory.ListLocalInventoriesRequest], + localinventory.ListLocalInventoriesResponse, + ]: # 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._ListLocalInventories(self._session, self._host, self._interceptor) # type: ignore + return self._ListLocalInventories(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -635,6 +765,4 @@ def close(self): self._session.close() -__all__=( - 'LocalInventoryServiceRestTransport', -) +__all__ = ("LocalInventoryServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/rest_base.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/rest_base.py similarity index 61% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/rest_base.py rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/rest_base.py index d556ef816975..19cc3b2646ff 100644 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/rest_base.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/local_inventory_service/transports/rest_base.py @@ -14,19 +14,17 @@ # 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 LocalInventoryServiceTransport, 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 empty_pb2 # type: ignore +from google.protobuf import json_format + from google.shopping.merchant_inventories_v1.types import localinventory +from .base import DEFAULT_CLIENT_INFO, LocalInventoryServiceTransport + class _BaseLocalInventoryServiceRestTransport(LocalInventoryServiceTransport): """Base REST backend transport for LocalInventoryService. @@ -41,14 +39,16 @@ class _BaseLocalInventoryServiceRestTransport(LocalInventoryServiceTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__(self, *, - host: str = 'merchantapi.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 = "merchantapi.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 +72,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,26 +85,30 @@ 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 _BaseDeleteLocalInventory: 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': '/inventories/v1/{name=accounts/*/products/*/localInventories/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/inventories/v1/{name=accounts/*/products/*/localInventories/*}", + }, ] return http_options @@ -114,11 +120,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(_BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._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( + _BaseLocalInventoryServiceRestTransport._BaseDeleteLocalInventory._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -127,20 +139,24 @@ class _BaseInsertLocalInventory: 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': '/inventories/v1/{parent=accounts/*/products/*}/localInventories:insert', - 'body': 'local_inventory', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/inventories/v1/{parent=accounts/*/products/*}/localInventories:insert", + "body": "local_inventory", + }, ] return http_options @@ -155,17 +171,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(_BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._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( + _BaseLocalInventoryServiceRestTransport._BaseInsertLocalInventory._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -174,19 +196,23 @@ class _BaseListLocalInventories: 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': '/inventories/v1/{parent=accounts/*/products/*}/localInventories', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/inventories/v1/{parent=accounts/*/products/*}/localInventories", + }, ] return http_options @@ -198,16 +224,20 @@ 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(_BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._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( + _BaseLocalInventoryServiceRestTransport._BaseListLocalInventories._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__=( - '_BaseLocalInventoryServiceRestTransport', -) +__all__ = ("_BaseLocalInventoryServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/__init__.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/__init__.py similarity index 89% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/__init__.py rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/__init__.py index 1a0839e5cff5..8607f7b9215c 100644 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/__init__.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import RegionalInventoryServiceClient from .async_client import RegionalInventoryServiceAsyncClient +from .client import RegionalInventoryServiceClient __all__ = ( - 'RegionalInventoryServiceClient', - 'RegionalInventoryServiceAsyncClient', + "RegionalInventoryServiceClient", + "RegionalInventoryServiceAsyncClient", ) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/async_client.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/async_client.py similarity index 79% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/async_client.py rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/async_client.py index 7b299ee89ed2..ce058dcfd256 100644 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/async_client.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/async_client.py @@ -13,42 +13,59 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import logging as std_logging from collections import OrderedDict +import logging as std_logging import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.shopping.merchant_inventories_v1 import gapic_version as package_version +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) -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.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf +from google.shopping.merchant_inventories_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore -from google.shopping.merchant_inventories_v1.services.regional_inventory_service import pagers -from google.shopping.merchant_inventories_v1.types import inventories_common -from google.shopping.merchant_inventories_v1.types import regionalinventory -from .transports.base import RegionalInventoryServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import RegionalInventoryServiceGrpcAsyncIOTransport +from google.shopping.merchant_inventories_v1.services.regional_inventory_service import ( + pagers, +) +from google.shopping.merchant_inventories_v1.types import ( + inventories_common, + regionalinventory, +) + from .client import RegionalInventoryServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, RegionalInventoryServiceTransport +from .transports.grpc_asyncio import RegionalInventoryServiceGrpcAsyncIOTransport 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 RegionalInventoryServiceAsyncClient: """Service to manage regional inventory for products. There is also separate ``regions`` resource and API to manage regions definitions. @@ -60,21 +77,45 @@ class RegionalInventoryServiceAsyncClient: # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. DEFAULT_ENDPOINT = RegionalInventoryServiceClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_ENDPOINT_TEMPLATE = ( + RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE + ) _DEFAULT_UNIVERSE = RegionalInventoryServiceClient._DEFAULT_UNIVERSE - regional_inventory_path = staticmethod(RegionalInventoryServiceClient.regional_inventory_path) - parse_regional_inventory_path = staticmethod(RegionalInventoryServiceClient.parse_regional_inventory_path) - common_billing_account_path = staticmethod(RegionalInventoryServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(RegionalInventoryServiceClient.parse_common_billing_account_path) + regional_inventory_path = staticmethod( + RegionalInventoryServiceClient.regional_inventory_path + ) + parse_regional_inventory_path = staticmethod( + RegionalInventoryServiceClient.parse_regional_inventory_path + ) + common_billing_account_path = staticmethod( + RegionalInventoryServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + RegionalInventoryServiceClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(RegionalInventoryServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(RegionalInventoryServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(RegionalInventoryServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(RegionalInventoryServiceClient.parse_common_organization_path) - common_project_path = staticmethod(RegionalInventoryServiceClient.common_project_path) - parse_common_project_path = staticmethod(RegionalInventoryServiceClient.parse_common_project_path) - common_location_path = staticmethod(RegionalInventoryServiceClient.common_location_path) - parse_common_location_path = staticmethod(RegionalInventoryServiceClient.parse_common_location_path) + parse_common_folder_path = staticmethod( + RegionalInventoryServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + RegionalInventoryServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + RegionalInventoryServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod( + RegionalInventoryServiceClient.common_project_path + ) + parse_common_project_path = staticmethod( + RegionalInventoryServiceClient.parse_common_project_path + ) + common_location_path = staticmethod( + RegionalInventoryServiceClient.common_location_path + ) + parse_common_location_path = staticmethod( + RegionalInventoryServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -110,7 +151,9 @@ 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: @@ -173,12 +216,20 @@ def universe_domain(self) -> str: get_transport_class = RegionalInventoryServiceClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, RegionalInventoryServiceTransport, Callable[..., RegionalInventoryServiceTransport]]] = "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, + RegionalInventoryServiceTransport, + Callable[..., RegionalInventoryServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the regional inventory service async client. Args: @@ -233,31 +284,41 @@ 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.shopping.merchant.inventories_v1.RegionalInventoryServiceAsyncClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.inventories.v1.RegionalInventoryService", - "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.shopping.merchant.inventories.v1.RegionalInventoryService", "credentialsType": None, - } + }, ) - async def list_regional_inventories(self, - request: Optional[Union[regionalinventory.ListRegionalInventoriesRequest, 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.ListRegionalInventoriesAsyncPager: + async def list_regional_inventories( + self, + request: Optional[ + Union[regionalinventory.ListRegionalInventoriesRequest, 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.ListRegionalInventoriesAsyncPager: r"""Lists the ``RegionalInventory`` resources for the given product in your merchant account. The response might contain fewer items than specified by ``pageSize``. If ``pageToken`` was returned in @@ -325,10 +386,14 @@ async def sample_list_regional_inventories(): # - 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. @@ -342,14 +407,14 @@ async def sample_list_regional_inventories(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_regional_inventories] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_regional_inventories + ] # 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. @@ -377,13 +442,16 @@ async def sample_list_regional_inventories(): # Done; return the response. return response - async def insert_regional_inventory(self, - request: Optional[Union[regionalinventory.InsertRegionalInventoryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> regionalinventory.RegionalInventory: + async def insert_regional_inventory( + self, + request: Optional[ + Union[regionalinventory.InsertRegionalInventoryRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regionalinventory.RegionalInventory: r"""Inserts a ``RegionalInventory`` to a given product in your merchant account. @@ -456,14 +524,14 @@ async def sample_insert_regional_inventory(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.insert_regional_inventory] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.insert_regional_inventory + ] # 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. @@ -480,14 +548,17 @@ async def sample_insert_regional_inventory(): # Done; return the response. return response - async def delete_regional_inventory(self, - request: Optional[Union[regionalinventory.DeleteRegionalInventoryRequest, dict]] = None, - *, - name: 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_regional_inventory( + self, + request: Optional[ + Union[regionalinventory.DeleteRegionalInventoryRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes the specified ``RegionalInventory`` resource from the given product in your merchant account. It might take up to an hour for the ``RegionalInventory`` to be deleted from the @@ -541,10 +612,14 @@ async def sample_delete_regional_inventory(): # - 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. @@ -558,14 +633,14 @@ async def sample_delete_regional_inventory(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_regional_inventory] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_regional_inventory + ] # 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. @@ -585,12 +660,13 @@ async def __aenter__(self) -> "RegionalInventoryServiceAsyncClient": 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__ = ( - "RegionalInventoryServiceAsyncClient", -) +__all__ = ("RegionalInventoryServiceAsyncClient",) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/client.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/client.py similarity index 78% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/client.py rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/client.py index 5726f494c2dd..5c646f5b6e76 100644 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/client.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/client.py @@ -19,22 +19,34 @@ import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) import warnings -from google.shopping.merchant_inventories_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.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf +from google.shopping.merchant_inventories_v1 import gapic_version as package_version + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -42,16 +54,22 @@ 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.shopping.merchant_inventories_v1.services.regional_inventory_service import pagers -from google.shopping.merchant_inventories_v1.types import inventories_common -from google.shopping.merchant_inventories_v1.types import regionalinventory -from .transports.base import RegionalInventoryServiceTransport, DEFAULT_CLIENT_INFO +from google.shopping.merchant_inventories_v1.services.regional_inventory_service import ( + pagers, +) +from google.shopping.merchant_inventories_v1.types import ( + inventories_common, + regionalinventory, +) + +from .transports.base import DEFAULT_CLIENT_INFO, RegionalInventoryServiceTransport from .transports.grpc import RegionalInventoryServiceGrpcTransport from .transports.grpc_asyncio import RegionalInventoryServiceGrpcAsyncIOTransport from .transports.rest import RegionalInventoryServiceRestTransport @@ -64,14 +82,18 @@ class RegionalInventoryServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[RegionalInventoryServiceTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[RegionalInventoryServiceTransport]] _transport_registry["grpc"] = RegionalInventoryServiceGrpcTransport _transport_registry["grpc_asyncio"] = RegionalInventoryServiceGrpcAsyncIOTransport _transport_registry["rest"] = RegionalInventoryServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[RegionalInventoryServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[RegionalInventoryServiceTransport]: """Returns an appropriate transport class. Args: @@ -165,8 +187,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: RegionalInventoryServiceClient: 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) @@ -183,73 +204,110 @@ def transport(self) -> RegionalInventoryServiceTransport: return self._transport @staticmethod - def regional_inventory_path(account: str,product: str,region: str,) -> str: + def regional_inventory_path( + account: str, + product: str, + region: str, + ) -> str: """Returns a fully-qualified regional_inventory string.""" - return "accounts/{account}/products/{product}/regionalInventories/{region}".format(account=account, product=product, region=region, ) + return ( + "accounts/{account}/products/{product}/regionalInventories/{region}".format( + account=account, + product=product, + region=region, + ) + ) @staticmethod - def parse_regional_inventory_path(path: str) -> Dict[str,str]: + def parse_regional_inventory_path(path: str) -> Dict[str, str]: """Parses a regional_inventory path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/products/(?P.+?)/regionalInventories/(?P.+?)$", path) + m = re.match( + r"^accounts/(?P.+?)/products/(?P.+?)/regionalInventories/(?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: @@ -281,16 +339,22 @@ 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 = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) 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 @@ -303,7 +367,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 @@ -324,13 +390,19 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) 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 == "true", use_mtls_endpoint, universe_domain_env @staticmethod @@ -353,7 +425,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: @@ -369,17 +443,27 @@ 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 = RegionalInventoryServiceClient._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 = RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = ( + RegionalInventoryServiceClient._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: @@ -415,15 +499,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 @@ -456,12 +543,20 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, RegionalInventoryServiceTransport, Callable[..., RegionalInventoryServiceTransport]]] = 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, + RegionalInventoryServiceTransport, + Callable[..., RegionalInventoryServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the regional inventory service client. Args: @@ -516,14 +611,26 @@ 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 = RegionalInventoryServiceClient._read_environment_variables() - self._client_cert_source = RegionalInventoryServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = RegionalInventoryServiceClient._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, + ) = RegionalInventoryServiceClient._read_environment_variables() + self._client_cert_source = ( + RegionalInventoryServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = RegionalInventoryServiceClient._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 @@ -534,7 +641,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 @@ -543,8 +652,10 @@ def __init__(self, *, if transport_provided: # transport is a RegionalInventoryServiceTransport 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 " @@ -553,20 +664,30 @@ def __init__(self, *, self._transport = cast(RegionalInventoryServiceTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - RegionalInventoryServiceClient._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or RegionalInventoryServiceClient._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[RegionalInventoryServiceTransport], Callable[..., RegionalInventoryServiceTransport]] = ( + transport_init: Union[ + Type[RegionalInventoryServiceTransport], + Callable[..., RegionalInventoryServiceTransport], + ] = ( RegionalInventoryServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., RegionalInventoryServiceTransport], transport) @@ -585,28 +706,39 @@ 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.shopping.merchant.inventories_v1.RegionalInventoryServiceClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.inventories.v1.RegionalInventoryService", - "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.shopping.merchant.inventories.v1.RegionalInventoryService", "credentialsType": None, - } + }, ) - def list_regional_inventories(self, - request: Optional[Union[regionalinventory.ListRegionalInventoriesRequest, 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.ListRegionalInventoriesPager: + def list_regional_inventories( + self, + request: Optional[ + Union[regionalinventory.ListRegionalInventoriesRequest, 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.ListRegionalInventoriesPager: r"""Lists the ``RegionalInventory`` resources for the given product in your merchant account. The response might contain fewer items than specified by ``pageSize``. If ``pageToken`` was returned in @@ -674,10 +806,14 @@ def sample_list_regional_inventories(): # - 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. @@ -690,14 +826,14 @@ def sample_list_regional_inventories(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_regional_inventories] + rpc = self._transport._wrapped_methods[ + self._transport.list_regional_inventories + ] # 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. @@ -725,13 +861,16 @@ def sample_list_regional_inventories(): # Done; return the response. return response - def insert_regional_inventory(self, - request: Optional[Union[regionalinventory.InsertRegionalInventoryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> regionalinventory.RegionalInventory: + def insert_regional_inventory( + self, + request: Optional[ + Union[regionalinventory.InsertRegionalInventoryRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regionalinventory.RegionalInventory: r"""Inserts a ``RegionalInventory`` to a given product in your merchant account. @@ -804,14 +943,14 @@ def sample_insert_regional_inventory(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.insert_regional_inventory] + rpc = self._transport._wrapped_methods[ + self._transport.insert_regional_inventory + ] # 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. @@ -828,14 +967,17 @@ def sample_insert_regional_inventory(): # Done; return the response. return response - def delete_regional_inventory(self, - request: Optional[Union[regionalinventory.DeleteRegionalInventoryRequest, dict]] = None, - *, - name: 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_regional_inventory( + self, + request: Optional[ + Union[regionalinventory.DeleteRegionalInventoryRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes the specified ``RegionalInventory`` resource from the given product in your merchant account. It might take up to an hour for the ``RegionalInventory`` to be deleted from the @@ -889,10 +1031,14 @@ def sample_delete_regional_inventory(): # - 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. @@ -905,14 +1051,14 @@ def sample_delete_regional_inventory(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_regional_inventory] + rpc = self._transport._wrapped_methods[ + self._transport.delete_regional_inventory + ] # 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. @@ -940,16 +1086,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__ = ( - "RegionalInventoryServiceClient", -) +__all__ = ("RegionalInventoryServiceClient",) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/pagers.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/pagers.py similarity index 77% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/pagers.py rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/pagers.py index 8cb98b71f403..f635262b633e 100644 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/pagers.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/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 ListRegionalInventoriesPager: 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[..., regionalinventory.ListRegionalInventoriesResponse], - request: regionalinventory.ListRegionalInventoriesRequest, - response: regionalinventory.ListRegionalInventoriesResponse, - *, - 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[..., regionalinventory.ListRegionalInventoriesResponse], + request: regionalinventory.ListRegionalInventoriesRequest, + response: regionalinventory.ListRegionalInventoriesResponse, + *, + 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[regionalinventory.ListRegionalInventoriesResponse]: 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[regionalinventory.RegionalInventory]: @@ -92,7 +114,7 @@ def __iter__(self) -> Iterator[regionalinventory.RegionalInventory]: yield from page.regional_inventories 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 ListRegionalInventoriesAsyncPager: @@ -112,14 +134,19 @@ class ListRegionalInventoriesAsyncPager: 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[regionalinventory.ListRegionalInventoriesResponse]], - request: regionalinventory.ListRegionalInventoriesRequest, - response: regionalinventory.ListRegionalInventoriesResponse, - *, - 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[regionalinventory.ListRegionalInventoriesResponse] + ], + request: regionalinventory.ListRegionalInventoriesRequest, + response: regionalinventory.ListRegionalInventoriesResponse, + *, + 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[regionalinventory.ListRegionalInventoriesResponse]: + async def pages( + self, + ) -> AsyncIterator[regionalinventory.ListRegionalInventoriesResponse]: 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[regionalinventory.RegionalInventory]: async def async_generator(): async for page in self.pages: @@ -163,4 +198,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/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/README.rst b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/README.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/README.rst rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/README.rst diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/__init__.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/__init__.py similarity index 59% rename from owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/__init__.py rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/__init__.py index b26a37767f11..94567bea861f 100644 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/regional_inventory_service/transports/__init__.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/__init__.py @@ -19,20 +19,23 @@ from .base import RegionalInventoryServiceTransport from .grpc import RegionalInventoryServiceGrpcTransport from .grpc_asyncio import RegionalInventoryServiceGrpcAsyncIOTransport -from .rest import RegionalInventoryServiceRestTransport -from .rest import RegionalInventoryServiceRestInterceptor - +from .rest import ( + RegionalInventoryServiceRestInterceptor, + RegionalInventoryServiceRestTransport, +) # Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[RegionalInventoryServiceTransport]] -_transport_registry['grpc'] = RegionalInventoryServiceGrpcTransport -_transport_registry['grpc_asyncio'] = RegionalInventoryServiceGrpcAsyncIOTransport -_transport_registry['rest'] = RegionalInventoryServiceRestTransport +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[RegionalInventoryServiceTransport]] +_transport_registry["grpc"] = RegionalInventoryServiceGrpcTransport +_transport_registry["grpc_asyncio"] = RegionalInventoryServiceGrpcAsyncIOTransport +_transport_registry["rest"] = RegionalInventoryServiceRestTransport __all__ = ( - 'RegionalInventoryServiceTransport', - 'RegionalInventoryServiceGrpcTransport', - 'RegionalInventoryServiceGrpcAsyncIOTransport', - 'RegionalInventoryServiceRestTransport', - 'RegionalInventoryServiceRestInterceptor', + "RegionalInventoryServiceTransport", + "RegionalInventoryServiceGrpcTransport", + "RegionalInventoryServiceGrpcAsyncIOTransport", + "RegionalInventoryServiceRestTransport", + "RegionalInventoryServiceRestInterceptor", ) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/base.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/base.py similarity index 66% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/base.py rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/base.py index 394c2cd125a5..184c9d359375 100644 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/base.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/base.py @@ -16,21 +16,22 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.shopping.merchant_inventories_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 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.protobuf import empty_pb2 # type: ignore + +from google.shopping.merchant_inventories_v1 import gapic_version as package_version from google.shopping.merchant_inventories_v1.types import regionalinventory -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 +40,23 @@ class RegionalInventoryServiceTransport(abc.ABC): """Abstract transport class for RegionalInventoryService.""" - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/content', - ) + AUTH_SCOPES = ("https://www.googleapis.com/auth/content",) - DEFAULT_HOST: str = 'merchantapi.googleapis.com' + DEFAULT_HOST: str = "merchantapi.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: @@ -92,30 +92,38 @@ 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_kwargs, quota_project_id=quota_project_id + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + 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,42 +148,48 @@ 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() @property - def list_regional_inventories(self) -> Callable[ - [regionalinventory.ListRegionalInventoriesRequest], - Union[ - regionalinventory.ListRegionalInventoriesResponse, - Awaitable[regionalinventory.ListRegionalInventoriesResponse] - ]]: + def list_regional_inventories( + self, + ) -> Callable[ + [regionalinventory.ListRegionalInventoriesRequest], + Union[ + regionalinventory.ListRegionalInventoriesResponse, + Awaitable[regionalinventory.ListRegionalInventoriesResponse], + ], + ]: raise NotImplementedError() @property - def insert_regional_inventory(self) -> Callable[ - [regionalinventory.InsertRegionalInventoryRequest], - Union[ - regionalinventory.RegionalInventory, - Awaitable[regionalinventory.RegionalInventory] - ]]: + def insert_regional_inventory( + self, + ) -> Callable[ + [regionalinventory.InsertRegionalInventoryRequest], + Union[ + regionalinventory.RegionalInventory, + Awaitable[regionalinventory.RegionalInventory], + ], + ]: raise NotImplementedError() @property - def delete_regional_inventory(self) -> Callable[ - [regionalinventory.DeleteRegionalInventoryRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_regional_inventory( + self, + ) -> Callable[ + [regionalinventory.DeleteRegionalInventoryRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property @@ -183,6 +197,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'RegionalInventoryServiceTransport', -) +__all__ = ("RegionalInventoryServiceTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/grpc.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/grpc.py similarity index 83% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/grpc.py rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/grpc.py index 40d2ac39f2b5..8fb9e407b06c 100644 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/grpc.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/grpc.py @@ -16,26 +16,26 @@ import json import logging as std_logging import pickle -import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # 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 from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf import empty_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message - import grpc # type: ignore import proto # type: ignore -from google.protobuf import empty_pb2 # type: ignore from google.shopping.merchant_inventories_v1.types import regionalinventory -from .base import RegionalInventoryServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, RegionalInventoryServiceTransport 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,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): @@ -66,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.shopping.merchant.inventories.v1.RegionalInventoryService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -77,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) @@ -92,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.shopping.merchant.inventories.v1.RegionalInventoryService", "rpcName": client_call_details.method, "response": grpc_response, @@ -115,23 +121,26 @@ class RegionalInventoryServiceGrpcTransport(RegionalInventoryServiceTransport): 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 = 'merchantapi.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 = "merchantapi.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: @@ -253,19 +262,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 = 'merchantapi.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 = "merchantapi.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. @@ -300,19 +313,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 list_regional_inventories(self) -> Callable[ - [regionalinventory.ListRegionalInventoriesRequest], - regionalinventory.ListRegionalInventoriesResponse]: + def list_regional_inventories( + self, + ) -> Callable[ + [regionalinventory.ListRegionalInventoriesRequest], + regionalinventory.ListRegionalInventoriesResponse, + ]: r"""Return a callable for the list regional inventories method over gRPC. Lists the ``RegionalInventory`` resources for the given product @@ -333,18 +348,21 @@ def list_regional_inventories(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_regional_inventories' not in self._stubs: - self._stubs['list_regional_inventories'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1.RegionalInventoryService/ListRegionalInventories', + if "list_regional_inventories" not in self._stubs: + self._stubs["list_regional_inventories"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.inventories.v1.RegionalInventoryService/ListRegionalInventories", request_serializer=regionalinventory.ListRegionalInventoriesRequest.serialize, response_deserializer=regionalinventory.ListRegionalInventoriesResponse.deserialize, ) - return self._stubs['list_regional_inventories'] + return self._stubs["list_regional_inventories"] @property - def insert_regional_inventory(self) -> Callable[ - [regionalinventory.InsertRegionalInventoryRequest], - regionalinventory.RegionalInventory]: + def insert_regional_inventory( + self, + ) -> Callable[ + [regionalinventory.InsertRegionalInventoryRequest], + regionalinventory.RegionalInventory, + ]: r"""Return a callable for the insert regional inventory method over gRPC. Inserts a ``RegionalInventory`` to a given product in your @@ -368,18 +386,18 @@ def insert_regional_inventory(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'insert_regional_inventory' not in self._stubs: - self._stubs['insert_regional_inventory'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1.RegionalInventoryService/InsertRegionalInventory', + if "insert_regional_inventory" not in self._stubs: + self._stubs["insert_regional_inventory"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.inventories.v1.RegionalInventoryService/InsertRegionalInventory", request_serializer=regionalinventory.InsertRegionalInventoryRequest.serialize, response_deserializer=regionalinventory.RegionalInventory.deserialize, ) - return self._stubs['insert_regional_inventory'] + return self._stubs["insert_regional_inventory"] @property - def delete_regional_inventory(self) -> Callable[ - [regionalinventory.DeleteRegionalInventoryRequest], - empty_pb2.Empty]: + def delete_regional_inventory( + self, + ) -> Callable[[regionalinventory.DeleteRegionalInventoryRequest], empty_pb2.Empty]: r"""Return a callable for the delete regional inventory method over gRPC. Deletes the specified ``RegionalInventory`` resource from the @@ -398,13 +416,13 @@ def delete_regional_inventory(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_regional_inventory' not in self._stubs: - self._stubs['delete_regional_inventory'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1.RegionalInventoryService/DeleteRegionalInventory', + if "delete_regional_inventory" not in self._stubs: + self._stubs["delete_regional_inventory"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.inventories.v1.RegionalInventoryService/DeleteRegionalInventory", request_serializer=regionalinventory.DeleteRegionalInventoryRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_regional_inventory'] + return self._stubs["delete_regional_inventory"] def close(self): self._logged_channel.close() @@ -414,6 +432,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'RegionalInventoryServiceGrpcTransport', -) +__all__ = ("RegionalInventoryServiceGrpcTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/grpc_asyncio.py similarity index 83% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/grpc_asyncio.py rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/grpc_asyncio.py index 334c40aab377..060948ad91c0 100644 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/grpc_asyncio.py @@ -15,31 +15,31 @@ # import inspect import json -import pickle import logging as std_logging -import warnings +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings -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 import empty_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore +import grpc # type: ignore from grpc.experimental import aio # type: ignore +import proto # type: ignore -from google.protobuf import empty_pb2 # type: ignore from google.shopping.merchant_inventories_v1.types import regionalinventory -from .base import RegionalInventoryServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, RegionalInventoryServiceTransport from .grpc import RegionalInventoryServiceGrpcTransport 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,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): @@ -70,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.shopping.merchant.inventories.v1.RegionalInventoryService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -81,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) @@ -96,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.shopping.merchant.inventories.v1.RegionalInventoryService", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -124,13 +132,15 @@ class RegionalInventoryServiceGrpcAsyncIOTransport(RegionalInventoryServiceTrans _stubs: Dict[str, Callable] = {} @classmethod - def create_channel(cls, - host: str = 'merchantapi.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 = "merchantapi.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. @@ -160,24 +170,26 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) - def __init__(self, *, - host: str = 'merchantapi.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 = "merchantapi.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: @@ -301,7 +313,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) @@ -316,9 +330,12 @@ def grpc_channel(self) -> aio.Channel: return self._grpc_channel @property - def list_regional_inventories(self) -> Callable[ - [regionalinventory.ListRegionalInventoriesRequest], - Awaitable[regionalinventory.ListRegionalInventoriesResponse]]: + def list_regional_inventories( + self, + ) -> Callable[ + [regionalinventory.ListRegionalInventoriesRequest], + Awaitable[regionalinventory.ListRegionalInventoriesResponse], + ]: r"""Return a callable for the list regional inventories method over gRPC. Lists the ``RegionalInventory`` resources for the given product @@ -339,18 +356,21 @@ def list_regional_inventories(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_regional_inventories' not in self._stubs: - self._stubs['list_regional_inventories'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1.RegionalInventoryService/ListRegionalInventories', + if "list_regional_inventories" not in self._stubs: + self._stubs["list_regional_inventories"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.inventories.v1.RegionalInventoryService/ListRegionalInventories", request_serializer=regionalinventory.ListRegionalInventoriesRequest.serialize, response_deserializer=regionalinventory.ListRegionalInventoriesResponse.deserialize, ) - return self._stubs['list_regional_inventories'] + return self._stubs["list_regional_inventories"] @property - def insert_regional_inventory(self) -> Callable[ - [regionalinventory.InsertRegionalInventoryRequest], - Awaitable[regionalinventory.RegionalInventory]]: + def insert_regional_inventory( + self, + ) -> Callable[ + [regionalinventory.InsertRegionalInventoryRequest], + Awaitable[regionalinventory.RegionalInventory], + ]: r"""Return a callable for the insert regional inventory method over gRPC. Inserts a ``RegionalInventory`` to a given product in your @@ -374,18 +394,20 @@ def insert_regional_inventory(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'insert_regional_inventory' not in self._stubs: - self._stubs['insert_regional_inventory'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1.RegionalInventoryService/InsertRegionalInventory', + if "insert_regional_inventory" not in self._stubs: + self._stubs["insert_regional_inventory"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.inventories.v1.RegionalInventoryService/InsertRegionalInventory", request_serializer=regionalinventory.InsertRegionalInventoryRequest.serialize, response_deserializer=regionalinventory.RegionalInventory.deserialize, ) - return self._stubs['insert_regional_inventory'] + return self._stubs["insert_regional_inventory"] @property - def delete_regional_inventory(self) -> Callable[ - [regionalinventory.DeleteRegionalInventoryRequest], - Awaitable[empty_pb2.Empty]]: + def delete_regional_inventory( + self, + ) -> Callable[ + [regionalinventory.DeleteRegionalInventoryRequest], Awaitable[empty_pb2.Empty] + ]: r"""Return a callable for the delete regional inventory method over gRPC. Deletes the specified ``RegionalInventory`` resource from the @@ -404,16 +426,16 @@ def delete_regional_inventory(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_regional_inventory' not in self._stubs: - self._stubs['delete_regional_inventory'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.inventories.v1.RegionalInventoryService/DeleteRegionalInventory', + if "delete_regional_inventory" not in self._stubs: + self._stubs["delete_regional_inventory"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.inventories.v1.RegionalInventoryService/DeleteRegionalInventory", request_serializer=regionalinventory.DeleteRegionalInventoryRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_regional_inventory'] + return self._stubs["delete_regional_inventory"] 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.list_regional_inventories: self._wrap_method( self.list_regional_inventories, @@ -445,6 +467,4 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ( - 'RegionalInventoryServiceGrpcAsyncIOTransport', -) +__all__ = ("RegionalInventoryServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/rest.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/rest.py similarity index 70% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/rest.py rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/rest.py index d9411c847f18..3c96db05aec4 100644 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/rest.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/rest.py @@ -13,32 +13,26 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import logging +import dataclasses import json # type: ignore +import logging +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings -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.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import gapic_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore import google.protobuf - +from google.protobuf import empty_pb2 # type: ignore from google.protobuf import json_format - from requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -from google.protobuf import empty_pb2 # type: ignore from google.shopping.merchant_inventories_v1.types import regionalinventory - -from .rest_base import _BaseRegionalInventoryServiceRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseRegionalInventoryServiceRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -47,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 @@ -103,7 +98,15 @@ def post_list_regional_inventories(self, response): """ - def pre_delete_regional_inventory(self, request: regionalinventory.DeleteRegionalInventoryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regionalinventory.DeleteRegionalInventoryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_delete_regional_inventory( + self, + request: regionalinventory.DeleteRegionalInventoryRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + regionalinventory.DeleteRegionalInventoryRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for delete_regional_inventory Override in a subclass to manipulate the request or metadata @@ -111,7 +114,14 @@ def pre_delete_regional_inventory(self, request: regionalinventory.DeleteRegiona """ return request, metadata - def pre_insert_regional_inventory(self, request: regionalinventory.InsertRegionalInventoryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regionalinventory.InsertRegionalInventoryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_insert_regional_inventory( + self, + request: regionalinventory.InsertRegionalInventoryRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + regionalinventory.InsertRegionalInventoryRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for insert_regional_inventory Override in a subclass to manipulate the request or metadata @@ -119,7 +129,9 @@ def pre_insert_regional_inventory(self, request: regionalinventory.InsertRegiona """ return request, metadata - def post_insert_regional_inventory(self, response: regionalinventory.RegionalInventory) -> regionalinventory.RegionalInventory: + def post_insert_regional_inventory( + self, response: regionalinventory.RegionalInventory + ) -> regionalinventory.RegionalInventory: """Post-rpc interceptor for insert_regional_inventory DEPRECATED. Please use the `post_insert_regional_inventory_with_metadata` @@ -132,7 +144,13 @@ def post_insert_regional_inventory(self, response: regionalinventory.RegionalInv """ return response - def post_insert_regional_inventory_with_metadata(self, response: regionalinventory.RegionalInventory, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regionalinventory.RegionalInventory, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_insert_regional_inventory_with_metadata( + self, + response: regionalinventory.RegionalInventory, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + regionalinventory.RegionalInventory, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for insert_regional_inventory Override in a subclass to read or manipulate the response or metadata after it @@ -147,7 +165,14 @@ def post_insert_regional_inventory_with_metadata(self, response: regionalinvento """ return response, metadata - def pre_list_regional_inventories(self, request: regionalinventory.ListRegionalInventoriesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regionalinventory.ListRegionalInventoriesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_regional_inventories( + self, + request: regionalinventory.ListRegionalInventoriesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + regionalinventory.ListRegionalInventoriesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for list_regional_inventories Override in a subclass to manipulate the request or metadata @@ -155,7 +180,9 @@ def pre_list_regional_inventories(self, request: regionalinventory.ListRegionalI """ return request, metadata - def post_list_regional_inventories(self, response: regionalinventory.ListRegionalInventoriesResponse) -> regionalinventory.ListRegionalInventoriesResponse: + def post_list_regional_inventories( + self, response: regionalinventory.ListRegionalInventoriesResponse + ) -> regionalinventory.ListRegionalInventoriesResponse: """Post-rpc interceptor for list_regional_inventories DEPRECATED. Please use the `post_list_regional_inventories_with_metadata` @@ -168,7 +195,14 @@ def post_list_regional_inventories(self, response: regionalinventory.ListRegiona """ return response - def post_list_regional_inventories_with_metadata(self, response: regionalinventory.ListRegionalInventoriesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regionalinventory.ListRegionalInventoriesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_regional_inventories_with_metadata( + self, + response: regionalinventory.ListRegionalInventoriesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + regionalinventory.ListRegionalInventoriesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for list_regional_inventories Override in a subclass to read or manipulate the response or metadata after it @@ -204,20 +238,21 @@ class RegionalInventoryServiceRestTransport(_BaseRegionalInventoryServiceRestTra It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__(self, *, - host: str = 'merchantapi.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[RegionalInventoryServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "merchantapi.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[RegionalInventoryServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -260,16 +295,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 RegionalInventoryServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _DeleteRegionalInventory(_BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory, RegionalInventoryServiceRestStub): + class _DeleteRegionalInventory( + _BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory, + RegionalInventoryServiceRestStub, + ): def __hash__(self): return hash("RegionalInventoryServiceRestTransport.DeleteRegionalInventory") @@ -281,26 +320,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: regionalinventory.DeleteRegionalInventoryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): + def __call__( + self, + request: regionalinventory.DeleteRegionalInventoryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): r"""Call the delete regional inventory method over HTTP. Args: @@ -316,30 +357,42 @@ def __call__(self, be of type `bytes`. """ - http_options = _BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._get_http_options() + http_options = ( + _BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._get_http_options() + ) - request, metadata = self._interceptor.pre_delete_regional_inventory(request, metadata) - transcoded_request = _BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_delete_regional_inventory( + request, metadata + ) + transcoded_request = _BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.shopping.merchant.inventories_v1.RegionalInventoryServiceClient.DeleteRegionalInventory", - extra = { + extra={ "serviceName": "google.shopping.merchant.inventories.v1.RegionalInventoryService", "rpcName": "DeleteRegionalInventory", "httpRequest": http_request, @@ -348,14 +401,24 @@ def __call__(self, ) # Send the request - response = RegionalInventoryServiceRestTransport._DeleteRegionalInventory._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = RegionalInventoryServiceRestTransport._DeleteRegionalInventory._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 _InsertRegionalInventory(_BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory, RegionalInventoryServiceRestStub): + class _InsertRegionalInventory( + _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory, + RegionalInventoryServiceRestStub, + ): def __hash__(self): return hash("RegionalInventoryServiceRestTransport.InsertRegionalInventory") @@ -367,27 +430,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: regionalinventory.InsertRegionalInventoryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> regionalinventory.RegionalInventory: + def __call__( + self, + request: regionalinventory.InsertRegionalInventoryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regionalinventory.RegionalInventory: r"""Call the insert regional inventory method over HTTP. Args: @@ -414,32 +479,46 @@ def __call__(self, """ - http_options = _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_http_options() + http_options = ( + _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_http_options() + ) - request, metadata = self._interceptor.pre_insert_regional_inventory(request, metadata) - transcoded_request = _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_insert_regional_inventory( + request, metadata + ) + transcoded_request = _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_transcoded_request( + http_options, request + ) - body = _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_request_body_json(transcoded_request) + body = _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.shopping.merchant.inventories_v1.RegionalInventoryServiceClient.InsertRegionalInventory", - extra = { + extra={ "serviceName": "google.shopping.merchant.inventories.v1.RegionalInventoryService", "rpcName": "InsertRegionalInventory", "httpRequest": http_request, @@ -448,7 +527,15 @@ def __call__(self, ) # Send the request - response = RegionalInventoryServiceRestTransport._InsertRegionalInventory._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = RegionalInventoryServiceRestTransport._InsertRegionalInventory._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. @@ -463,20 +550,26 @@ def __call__(self, resp = self._interceptor.post_insert_regional_inventory(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_insert_regional_inventory_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_insert_regional_inventory_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = regionalinventory.RegionalInventory.to_json(response) + response_payload = regionalinventory.RegionalInventory.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.shopping.merchant.inventories_v1.RegionalInventoryServiceClient.insert_regional_inventory", - extra = { + extra={ "serviceName": "google.shopping.merchant.inventories.v1.RegionalInventoryService", "rpcName": "InsertRegionalInventory", "metadata": http_response["headers"], @@ -485,7 +578,10 @@ def __call__(self, ) return resp - class _ListRegionalInventories(_BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories, RegionalInventoryServiceRestStub): + class _ListRegionalInventories( + _BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories, + RegionalInventoryServiceRestStub, + ): def __hash__(self): return hash("RegionalInventoryServiceRestTransport.ListRegionalInventories") @@ -497,26 +593,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: regionalinventory.ListRegionalInventoriesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> regionalinventory.ListRegionalInventoriesResponse: + def __call__( + self, + request: regionalinventory.ListRegionalInventoriesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regionalinventory.ListRegionalInventoriesResponse: r"""Call the list regional inventories method over HTTP. Args: @@ -538,30 +636,42 @@ def __call__(self, """ - http_options = _BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._get_http_options() + http_options = ( + _BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._get_http_options() + ) - request, metadata = self._interceptor.pre_list_regional_inventories(request, metadata) - transcoded_request = _BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_list_regional_inventories( + request, metadata + ) + transcoded_request = _BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.shopping.merchant.inventories_v1.RegionalInventoryServiceClient.ListRegionalInventories", - extra = { + extra={ "serviceName": "google.shopping.merchant.inventories.v1.RegionalInventoryService", "rpcName": "ListRegionalInventories", "httpRequest": http_request, @@ -570,7 +680,14 @@ def __call__(self, ) # Send the request - response = RegionalInventoryServiceRestTransport._ListRegionalInventories._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = RegionalInventoryServiceRestTransport._ListRegionalInventories._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -585,20 +702,28 @@ def __call__(self, resp = self._interceptor.post_list_regional_inventories(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_regional_inventories_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_regional_inventories_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = regionalinventory.ListRegionalInventoriesResponse.to_json(response) + response_payload = ( + regionalinventory.ListRegionalInventoriesResponse.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.shopping.merchant.inventories_v1.RegionalInventoryServiceClient.list_regional_inventories", - extra = { + extra={ "serviceName": "google.shopping.merchant.inventories.v1.RegionalInventoryService", "rpcName": "ListRegionalInventories", "metadata": http_response["headers"], @@ -608,28 +733,34 @@ def __call__(self, return resp @property - def delete_regional_inventory(self) -> Callable[ - [regionalinventory.DeleteRegionalInventoryRequest], - empty_pb2.Empty]: + def delete_regional_inventory( + self, + ) -> Callable[[regionalinventory.DeleteRegionalInventoryRequest], 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._DeleteRegionalInventory(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteRegionalInventory(self._session, self._host, self._interceptor) # type: ignore @property - def insert_regional_inventory(self) -> Callable[ - [regionalinventory.InsertRegionalInventoryRequest], - regionalinventory.RegionalInventory]: + def insert_regional_inventory( + self, + ) -> Callable[ + [regionalinventory.InsertRegionalInventoryRequest], + regionalinventory.RegionalInventory, + ]: # 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._InsertRegionalInventory(self._session, self._host, self._interceptor) # type: ignore + return self._InsertRegionalInventory(self._session, self._host, self._interceptor) # type: ignore @property - def list_regional_inventories(self) -> Callable[ - [regionalinventory.ListRegionalInventoriesRequest], - regionalinventory.ListRegionalInventoriesResponse]: + def list_regional_inventories( + self, + ) -> Callable[ + [regionalinventory.ListRegionalInventoriesRequest], + regionalinventory.ListRegionalInventoriesResponse, + ]: # 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._ListRegionalInventories(self._session, self._host, self._interceptor) # type: ignore + return self._ListRegionalInventories(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -639,6 +770,4 @@ def close(self): self._session.close() -__all__=( - 'RegionalInventoryServiceRestTransport', -) +__all__ = ("RegionalInventoryServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/rest_base.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/rest_base.py similarity index 61% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/rest_base.py rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/rest_base.py index 286531c5fe10..a093a2037b13 100644 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/rest_base.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/services/regional_inventory_service/transports/rest_base.py @@ -14,19 +14,17 @@ # 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 RegionalInventoryServiceTransport, 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 empty_pb2 # type: ignore +from google.protobuf import json_format + from google.shopping.merchant_inventories_v1.types import regionalinventory +from .base import DEFAULT_CLIENT_INFO, RegionalInventoryServiceTransport + class _BaseRegionalInventoryServiceRestTransport(RegionalInventoryServiceTransport): """Base REST backend transport for RegionalInventoryService. @@ -41,14 +39,16 @@ class _BaseRegionalInventoryServiceRestTransport(RegionalInventoryServiceTranspo It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__(self, *, - host: str = 'merchantapi.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 = "merchantapi.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 +72,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,26 +85,30 @@ 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 _BaseDeleteRegionalInventory: 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': '/inventories/v1/{name=accounts/*/products/*/regionalInventories/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/inventories/v1/{name=accounts/*/products/*/regionalInventories/*}", + }, ] return http_options @@ -114,11 +120,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(_BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._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( + _BaseRegionalInventoryServiceRestTransport._BaseDeleteRegionalInventory._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -127,20 +139,24 @@ class _BaseInsertRegionalInventory: 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': '/inventories/v1/{parent=accounts/*/products/*}/regionalInventories:insert', - 'body': 'regional_inventory', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/inventories/v1/{parent=accounts/*/products/*}/regionalInventories:insert", + "body": "regional_inventory", + }, ] return http_options @@ -155,17 +171,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(_BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._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( + _BaseRegionalInventoryServiceRestTransport._BaseInsertRegionalInventory._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -174,19 +196,23 @@ class _BaseListRegionalInventories: 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': '/inventories/v1/{parent=accounts/*/products/*}/regionalInventories', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/inventories/v1/{parent=accounts/*/products/*}/regionalInventories", + }, ] return http_options @@ -198,16 +224,20 @@ 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(_BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._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( + _BaseRegionalInventoryServiceRestTransport._BaseListRegionalInventories._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__=( - '_BaseRegionalInventoryServiceRestTransport', -) +__all__ = ("_BaseRegionalInventoryServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/__init__.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/types/__init__.py similarity index 67% rename from owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/__init__.py rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/types/__init__.py index 77bed1ea7dce..aea17e889fbb 100644 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/types/__init__.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/types/__init__.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from .inventories_common import LocalInventoryAttributes, RegionalInventoryAttributes from .localinventory import ( DeleteLocalInventoryRequest, InsertLocalInventoryRequest, @@ -29,14 +30,16 @@ ) __all__ = ( - 'DeleteLocalInventoryRequest', - 'InsertLocalInventoryRequest', - 'ListLocalInventoriesRequest', - 'ListLocalInventoriesResponse', - 'LocalInventory', - 'DeleteRegionalInventoryRequest', - 'InsertRegionalInventoryRequest', - 'ListRegionalInventoriesRequest', - 'ListRegionalInventoriesResponse', - 'RegionalInventory', + "LocalInventoryAttributes", + "RegionalInventoryAttributes", + "DeleteLocalInventoryRequest", + "InsertLocalInventoryRequest", + "ListLocalInventoriesRequest", + "ListLocalInventoriesResponse", + "LocalInventory", + "DeleteRegionalInventoryRequest", + "InsertRegionalInventoryRequest", + "ListRegionalInventoriesRequest", + "ListRegionalInventoriesResponse", + "RegionalInventory", ) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/inventories_common.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/types/inventories_common.py similarity index 98% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/inventories_common.py rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/types/inventories_common.py index 76aa3a64cb07..0a1af19e0a7f 100644 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/inventories_common.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/types/inventories_common.py @@ -17,17 +17,15 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.shopping.type.types import types from google.type import interval_pb2 # type: ignore - +import proto # type: ignore __protobuf__ = proto.module( - package='google.shopping.merchant.inventories.v1', + package="google.shopping.merchant.inventories.v1", manifest={ - 'LocalInventoryAttributes', - 'RegionalInventoryAttributes', + "LocalInventoryAttributes", + "RegionalInventoryAttributes", }, ) @@ -79,6 +77,7 @@ class LocalInventoryAttributes(proto.Message): This field is a member of `oneof`_ ``_instore_product_location``. """ + class Availability(proto.Enum): r"""`Availability `__ of the product at this store. @@ -238,6 +237,7 @@ class RegionalInventoryAttributes(proto.Message): This field is a member of `oneof`_ ``_availability``. """ + class Availability(proto.Enum): r"""`Availability `__ of the product in this region. diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/localinventory.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/types/localinventory.py similarity index 91% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/localinventory.py rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/types/localinventory.py index 2cbebf9dbf5a..78fc2e8c8ebf 100644 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/localinventory.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/types/localinventory.py @@ -21,15 +21,14 @@ from google.shopping.merchant_inventories_v1.types import inventories_common - __protobuf__ = proto.module( - package='google.shopping.merchant.inventories.v1', + package="google.shopping.merchant.inventories.v1", manifest={ - 'LocalInventory', - 'ListLocalInventoriesRequest', - 'ListLocalInventoriesResponse', - 'InsertLocalInventoryRequest', - 'DeleteLocalInventoryRequest', + "LocalInventory", + "ListLocalInventoriesRequest", + "ListLocalInventoriesResponse", + "InsertLocalInventoryRequest", + "DeleteLocalInventoryRequest", }, ) @@ -74,10 +73,12 @@ class LocalInventory(proto.Message): proto.STRING, number=3, ) - local_inventory_attributes: inventories_common.LocalInventoryAttributes = proto.Field( - proto.MESSAGE, - number=14, - message=inventories_common.LocalInventoryAttributes, + local_inventory_attributes: inventories_common.LocalInventoryAttributes = ( + proto.Field( + proto.MESSAGE, + number=14, + message=inventories_common.LocalInventoryAttributes, + ) ) @@ -140,10 +141,10 @@ class ListLocalInventoriesResponse(proto.Message): def raw_page(self): return self - local_inventories: MutableSequence['LocalInventory'] = proto.RepeatedField( + local_inventories: MutableSequence["LocalInventory"] = proto.RepeatedField( proto.MESSAGE, number=1, - message='LocalInventory', + message="LocalInventory", ) next_page_token: str = proto.Field( proto.STRING, @@ -170,10 +171,10 @@ class InsertLocalInventoryRequest(proto.Message): proto.STRING, number=1, ) - local_inventory: 'LocalInventory' = proto.Field( + local_inventory: "LocalInventory" = proto.Field( proto.MESSAGE, number=2, - message='LocalInventory', + message="LocalInventory", ) diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/regionalinventory.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/types/regionalinventory.py similarity index 90% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/regionalinventory.py rename to packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/types/regionalinventory.py index ecf87fc3b24e..ca1738897e4b 100644 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/google/shopping/merchant_inventories_v1/types/regionalinventory.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/types/regionalinventory.py @@ -21,15 +21,14 @@ from google.shopping.merchant_inventories_v1.types import inventories_common - __protobuf__ = proto.module( - package='google.shopping.merchant.inventories.v1', + package="google.shopping.merchant.inventories.v1", manifest={ - 'RegionalInventory', - 'ListRegionalInventoriesRequest', - 'ListRegionalInventoriesResponse', - 'InsertRegionalInventoryRequest', - 'DeleteRegionalInventoryRequest', + "RegionalInventory", + "ListRegionalInventoriesRequest", + "ListRegionalInventoriesResponse", + "InsertRegionalInventoryRequest", + "DeleteRegionalInventoryRequest", }, ) @@ -75,10 +74,12 @@ class RegionalInventory(proto.Message): proto.STRING, number=3, ) - regional_inventory_attributes: inventories_common.RegionalInventoryAttributes = proto.Field( - proto.MESSAGE, - number=9, - message=inventories_common.RegionalInventoryAttributes, + regional_inventory_attributes: inventories_common.RegionalInventoryAttributes = ( + proto.Field( + proto.MESSAGE, + number=9, + message=inventories_common.RegionalInventoryAttributes, + ) ) @@ -141,10 +142,10 @@ class ListRegionalInventoriesResponse(proto.Message): def raw_page(self): return self - regional_inventories: MutableSequence['RegionalInventory'] = proto.RepeatedField( + regional_inventories: MutableSequence["RegionalInventory"] = proto.RepeatedField( proto.MESSAGE, number=1, - message='RegionalInventory', + message="RegionalInventory", ) next_page_token: str = proto.Field( proto.STRING, @@ -171,10 +172,10 @@ class InsertRegionalInventoryRequest(proto.Message): proto.STRING, number=1, ) - regional_inventory: 'RegionalInventory' = proto.Field( + regional_inventory: "RegionalInventory" = proto.Field( proto.MESSAGE, number=2, - message='RegionalInventory', + message="RegionalInventory", ) diff --git a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/gapic_version.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/gapic_version.py index 1f20decfc02d..20a9cd975b02 100644 --- a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/gapic_version.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.15" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_delete_local_inventory_async.py b/packages/google-shopping-merchant-inventories/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_delete_local_inventory_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_delete_local_inventory_async.py rename to packages/google-shopping-merchant-inventories/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_delete_local_inventory_async.py diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_delete_local_inventory_sync.py b/packages/google-shopping-merchant-inventories/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_delete_local_inventory_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_delete_local_inventory_sync.py rename to packages/google-shopping-merchant-inventories/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_delete_local_inventory_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_insert_local_inventory_async.py b/packages/google-shopping-merchant-inventories/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_insert_local_inventory_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_insert_local_inventory_async.py rename to packages/google-shopping-merchant-inventories/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_insert_local_inventory_async.py diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_insert_local_inventory_sync.py b/packages/google-shopping-merchant-inventories/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_insert_local_inventory_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_insert_local_inventory_sync.py rename to packages/google-shopping-merchant-inventories/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_insert_local_inventory_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_list_local_inventories_async.py b/packages/google-shopping-merchant-inventories/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_list_local_inventories_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_list_local_inventories_async.py rename to packages/google-shopping-merchant-inventories/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_list_local_inventories_async.py diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_list_local_inventories_sync.py b/packages/google-shopping-merchant-inventories/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_list_local_inventories_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_list_local_inventories_sync.py rename to packages/google-shopping-merchant-inventories/samples/generated_samples/merchantapi_v1_generated_local_inventory_service_list_local_inventories_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_delete_regional_inventory_async.py b/packages/google-shopping-merchant-inventories/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_delete_regional_inventory_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_delete_regional_inventory_async.py rename to packages/google-shopping-merchant-inventories/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_delete_regional_inventory_async.py diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_delete_regional_inventory_sync.py b/packages/google-shopping-merchant-inventories/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_delete_regional_inventory_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_delete_regional_inventory_sync.py rename to packages/google-shopping-merchant-inventories/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_delete_regional_inventory_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_insert_regional_inventory_async.py b/packages/google-shopping-merchant-inventories/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_insert_regional_inventory_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_insert_regional_inventory_async.py rename to packages/google-shopping-merchant-inventories/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_insert_regional_inventory_async.py diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_insert_regional_inventory_sync.py b/packages/google-shopping-merchant-inventories/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_insert_regional_inventory_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_insert_regional_inventory_sync.py rename to packages/google-shopping-merchant-inventories/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_insert_regional_inventory_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_list_regional_inventories_async.py b/packages/google-shopping-merchant-inventories/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_list_regional_inventories_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_list_regional_inventories_async.py rename to packages/google-shopping-merchant-inventories/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_list_regional_inventories_async.py diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_list_regional_inventories_sync.py b/packages/google-shopping-merchant-inventories/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_list_regional_inventories_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_list_regional_inventories_sync.py rename to packages/google-shopping-merchant-inventories/samples/generated_samples/merchantapi_v1_generated_regional_inventory_service_list_regional_inventories_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1.json b/packages/google-shopping-merchant-inventories/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1.json similarity index 100% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1.json rename to packages/google-shopping-merchant-inventories/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1.json diff --git a/packages/google-shopping-merchant-inventories/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1beta.json b/packages/google-shopping-merchant-inventories/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1beta.json index 29d6b1a52c33..73ddfcf94070 100644 --- a/packages/google-shopping-merchant-inventories/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1beta.json +++ b/packages/google-shopping-merchant-inventories/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-shopping-merchant-inventories", - "version": "0.1.15" + "version": "0.1.0" }, "snippets": [ { diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/scripts/fixup_merchant_inventories_v1_keywords.py b/packages/google-shopping-merchant-inventories/scripts/fixup_merchant_inventories_v1_keywords.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/scripts/fixup_merchant_inventories_v1_keywords.py rename to packages/google-shopping-merchant-inventories/scripts/fixup_merchant_inventories_v1_keywords.py diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/__init__.py b/packages/google-shopping-merchant-inventories/tests/unit/gapic/merchant_inventories_v1/__init__.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-inventories/v1beta/google/shopping/merchant_inventories_v1beta/services/__init__.py rename to packages/google-shopping-merchant-inventories/tests/unit/gapic/merchant_inventories_v1/__init__.py diff --git a/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/merchant_inventories_v1/test_local_inventory_service.py b/packages/google-shopping-merchant-inventories/tests/unit/gapic/merchant_inventories_v1/test_local_inventory_service.py similarity index 68% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/merchant_inventories_v1/test_local_inventory_service.py rename to packages/google-shopping-merchant-inventories/tests/unit/gapic/merchant_inventories_v1/test_local_inventory_service.py index a2a0b428a3f0..35691e465f04 100644 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/merchant_inventories_v1/test_local_inventory_service.py +++ b/packages/google-shopping-merchant-inventories/tests/unit/gapic/merchant_inventories_v1/test_local_inventory_service.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,49 +22,49 @@ 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 +from collections.abc import AsyncIterable, Iterable import json import math -import pytest + from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule +from google.protobuf import json_format +import grpc +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 +import pytest +from requests import PreparedRequest, Request, Response 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.oauth2 import service_account from google.protobuf import timestamp_pb2 # type: ignore -from google.shopping.merchant_inventories_v1.services.local_inventory_service import LocalInventoryServiceAsyncClient -from google.shopping.merchant_inventories_v1.services.local_inventory_service import LocalInventoryServiceClient -from google.shopping.merchant_inventories_v1.services.local_inventory_service import pagers -from google.shopping.merchant_inventories_v1.services.local_inventory_service import transports -from google.shopping.merchant_inventories_v1.types import inventories_common -from google.shopping.merchant_inventories_v1.types import localinventory from google.shopping.type.types import types from google.type import interval_pb2 # type: ignore -import google.auth - +from google.shopping.merchant_inventories_v1.services.local_inventory_service import ( + LocalInventoryServiceAsyncClient, + LocalInventoryServiceClient, + pagers, + transports, +) +from google.shopping.merchant_inventories_v1.types import ( + inventories_common, + localinventory, +) CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -78,9 +79,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(): @@ -88,17 +91,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(): @@ -109,101 +122,245 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert LocalInventoryServiceClient._get_default_mtls_endpoint(None) is None - assert LocalInventoryServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert LocalInventoryServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert LocalInventoryServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert LocalInventoryServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert LocalInventoryServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ( + LocalInventoryServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + LocalInventoryServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + LocalInventoryServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + LocalInventoryServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + LocalInventoryServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + def test__read_environment_variables(): - assert LocalInventoryServiceClient._read_environment_variables() == (False, "auto", None) + assert LocalInventoryServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert LocalInventoryServiceClient._read_environment_variables() == (True, "auto", None) + assert LocalInventoryServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert LocalInventoryServiceClient._read_environment_variables() == (False, "auto", None) + assert LocalInventoryServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) - 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) as excinfo: LocalInventoryServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert LocalInventoryServiceClient._read_environment_variables() == (False, "never", None) + assert LocalInventoryServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert LocalInventoryServiceClient._read_environment_variables() == (False, "always", None) + assert LocalInventoryServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert LocalInventoryServiceClient._read_environment_variables() == (False, "auto", None) + assert LocalInventoryServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: LocalInventoryServiceClient._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 LocalInventoryServiceClient._read_environment_variables() == (False, "auto", "foo.com") + assert LocalInventoryServiceClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + def test__get_client_cert_source(): mock_provided_cert_source = mock.Mock() mock_default_cert_source = mock.Mock() assert LocalInventoryServiceClient._get_client_cert_source(None, False) is None - assert LocalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert LocalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + assert ( + LocalInventoryServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + LocalInventoryServiceClient._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 ( + LocalInventoryServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + LocalInventoryServiceClient._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 LocalInventoryServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert LocalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source -@mock.patch.object(LocalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceClient)) -@mock.patch.object(LocalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceAsyncClient)) +@mock.patch.object( + LocalInventoryServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(LocalInventoryServiceClient), +) +@mock.patch.object( + LocalInventoryServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(LocalInventoryServiceAsyncClient), +) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = LocalInventoryServiceClient._DEFAULT_UNIVERSE - default_endpoint = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) - assert LocalInventoryServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert LocalInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - assert LocalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert LocalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "always") == LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - assert LocalInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - assert LocalInventoryServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert LocalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + assert ( + LocalInventoryServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + LocalInventoryServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + LocalInventoryServiceClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + LocalInventoryServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + LocalInventoryServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == LocalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + LocalInventoryServiceClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + LocalInventoryServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) with pytest.raises(MutualTLSChannelError) as excinfo: - LocalInventoryServiceClient._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." + LocalInventoryServiceClient._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 LocalInventoryServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert LocalInventoryServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert LocalInventoryServiceClient._get_universe_domain(None, None) == LocalInventoryServiceClient._DEFAULT_UNIVERSE + assert ( + LocalInventoryServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + LocalInventoryServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + LocalInventoryServiceClient._get_universe_domain(None, None) + == LocalInventoryServiceClient._DEFAULT_UNIVERSE + ) with pytest.raises(ValueError) as excinfo: LocalInventoryServiceClient._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) @@ -219,7 +376,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") @@ -232,14 +390,22 @@ 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", [ - (LocalInventoryServiceClient, "grpc"), - (LocalInventoryServiceAsyncClient, "grpc_asyncio"), - (LocalInventoryServiceClient, "rest"), -]) -def test_local_inventory_service_client_from_service_account_info(client_class, transport_name): + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (LocalInventoryServiceClient, "grpc"), + (LocalInventoryServiceAsyncClient, "grpc_asyncio"), + (LocalInventoryServiceClient, "rest"), + ], +) +def test_local_inventory_service_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) @@ -247,52 +413,70 @@ def test_local_inventory_service_client_from_service_account_info(client_class, assert isinstance(client, client_class) assert client.transport._host == ( - 'merchantapi.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://merchantapi.googleapis.com' + "merchantapi.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://merchantapi.googleapis.com" ) -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.LocalInventoryServiceGrpcTransport, "grpc"), - (transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.LocalInventoryServiceRestTransport, "rest"), -]) -def test_local_inventory_service_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.LocalInventoryServiceGrpcTransport, "grpc"), + (transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.LocalInventoryServiceRestTransport, "rest"), + ], +) +def test_local_inventory_service_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", [ - (LocalInventoryServiceClient, "grpc"), - (LocalInventoryServiceAsyncClient, "grpc_asyncio"), - (LocalInventoryServiceClient, "rest"), -]) -def test_local_inventory_service_client_from_service_account_file(client_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (LocalInventoryServiceClient, "grpc"), + (LocalInventoryServiceAsyncClient, "grpc_asyncio"), + (LocalInventoryServiceClient, "rest"), + ], +) +def test_local_inventory_service_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 == ( - 'merchantapi.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://merchantapi.googleapis.com' + "merchantapi.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://merchantapi.googleapis.com" ) @@ -308,30 +492,53 @@ def test_local_inventory_service_client_get_transport_class(): assert transport == transports.LocalInventoryServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc"), - (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest"), -]) -@mock.patch.object(LocalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceClient)) -@mock.patch.object(LocalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceAsyncClient)) -def test_local_inventory_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + LocalInventoryServiceClient, + transports.LocalInventoryServiceGrpcTransport, + "grpc", + ), + ( + LocalInventoryServiceAsyncClient, + transports.LocalInventoryServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + LocalInventoryServiceClient, + transports.LocalInventoryServiceRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + LocalInventoryServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(LocalInventoryServiceClient), +) +@mock.patch.object( + LocalInventoryServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(LocalInventoryServiceAsyncClient), +) +def test_local_inventory_service_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(LocalInventoryServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object(LocalInventoryServiceClient, "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(LocalInventoryServiceClient, 'get_transport_class') as gtc: + with mock.patch.object(LocalInventoryServiceClient, "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( @@ -349,13 +556,15 @@ def test_local_inventory_service_client_client_options(client_class, transport_c # 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, @@ -367,7 +576,7 @@ def test_local_inventory_service_client_client_options(client_class, transport_c # 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( @@ -387,23 +596,33 @@ def test_local_inventory_service_client_client_options(client_class, transport_c 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 GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - 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) as excinfo: client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) # 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", @@ -412,48 +631,102 @@ def test_local_inventory_service_client_client_options(client_class, transport_c 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", [ - (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc", "true"), - (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc", "false"), - (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest", "true"), - (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(LocalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceClient)) -@mock.patch.object(LocalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + LocalInventoryServiceClient, + transports.LocalInventoryServiceGrpcTransport, + "grpc", + "true", + ), + ( + LocalInventoryServiceAsyncClient, + transports.LocalInventoryServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + LocalInventoryServiceClient, + transports.LocalInventoryServiceGrpcTransport, + "grpc", + "false", + ), + ( + LocalInventoryServiceAsyncClient, + transports.LocalInventoryServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + LocalInventoryServiceClient, + transports.LocalInventoryServiceRestTransport, + "rest", + "true", + ), + ( + LocalInventoryServiceClient, + transports.LocalInventoryServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + LocalInventoryServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(LocalInventoryServiceClient), +) +@mock.patch.object( + LocalInventoryServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(LocalInventoryServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_local_inventory_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_local_inventory_service_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 @@ -472,12 +745,22 @@ def test_local_inventory_service_client_mtls_env_auto(client_class, transport_cl # 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 @@ -498,15 +781,22 @@ def test_local_inventory_service_client_mtls_env_auto(client_class, transport_cl ) # 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, @@ -516,19 +806,31 @@ def test_local_inventory_service_client_mtls_env_auto(client_class, transport_cl ) -@pytest.mark.parametrize("client_class", [ - LocalInventoryServiceClient, LocalInventoryServiceAsyncClient -]) -@mock.patch.object(LocalInventoryServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LocalInventoryServiceClient)) -@mock.patch.object(LocalInventoryServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LocalInventoryServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", [LocalInventoryServiceClient, LocalInventoryServiceAsyncClient] +) +@mock.patch.object( + LocalInventoryServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(LocalInventoryServiceClient), +) +@mock.patch.object( + LocalInventoryServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(LocalInventoryServiceAsyncClient), +) def test_local_inventory_service_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 @@ -536,8 +838,12 @@ def test_local_inventory_service_client_get_mtls_endpoint_and_cert_source(client 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 @@ -555,16 +861,28 @@ def test_local_inventory_service_client_get_mtls_endpoint_and_cert_source(client # 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 @@ -574,34 +892,62 @@ def test_local_inventory_service_client_get_mtls_endpoint_and_cert_source(client 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`" + ) # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - 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) as excinfo: client_class.get_mtls_endpoint_and_cert_source() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + -@pytest.mark.parametrize("client_class", [ - LocalInventoryServiceClient, LocalInventoryServiceAsyncClient -]) -@mock.patch.object(LocalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceClient)) -@mock.patch.object(LocalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LocalInventoryServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", [LocalInventoryServiceClient, LocalInventoryServiceAsyncClient] +) +@mock.patch.object( + LocalInventoryServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(LocalInventoryServiceClient), +) +@mock.patch.object( + LocalInventoryServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(LocalInventoryServiceAsyncClient), +) def test_local_inventory_service_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = LocalInventoryServiceClient._DEFAULT_UNIVERSE - default_endpoint = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = LocalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = LocalInventoryServiceClient._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", @@ -624,11 +970,19 @@ def test_local_inventory_service_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. @@ -636,27 +990,48 @@ def test_local_inventory_service_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", [ - (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc"), - (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest"), -]) -def test_local_inventory_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + LocalInventoryServiceClient, + transports.LocalInventoryServiceGrpcTransport, + "grpc", + ), + ( + LocalInventoryServiceAsyncClient, + transports.LocalInventoryServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + LocalInventoryServiceClient, + transports.LocalInventoryServiceRestTransport, + "rest", + ), + ], +) +def test_local_inventory_service_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, @@ -665,24 +1040,45 @@ def test_local_inventory_service_client_client_options_scopes(client_class, tran api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc", grpc_helpers), - (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (LocalInventoryServiceClient, transports.LocalInventoryServiceRestTransport, "rest", None), -]) -def test_local_inventory_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + LocalInventoryServiceClient, + transports.LocalInventoryServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + LocalInventoryServiceAsyncClient, + transports.LocalInventoryServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + LocalInventoryServiceClient, + transports.LocalInventoryServiceRestTransport, + "rest", + None, + ), + ], +) +def test_local_inventory_service_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, @@ -691,11 +1087,14 @@ def test_local_inventory_service_client_client_options_credentials_file(client_c api_audience=None, ) + def test_local_inventory_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_inventories_v1.services.local_inventory_service.transports.LocalInventoryServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.shopping.merchant_inventories_v1.services.local_inventory_service.transports.LocalInventoryServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = LocalInventoryServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -710,23 +1109,38 @@ def test_local_inventory_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport, "grpc", grpc_helpers), - (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_local_inventory_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + LocalInventoryServiceClient, + transports.LocalInventoryServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + LocalInventoryServiceAsyncClient, + transports.LocalInventoryServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_local_inventory_service_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, @@ -753,9 +1167,7 @@ def test_local_inventory_service_client_create_channel_credentials_file(client_c credentials=file_creds, credentials_file=None, quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/content', -), + default_scopes=("https://www.googleapis.com/auth/content",), scopes=None, default_host="merchantapi.googleapis.com", ssl_credentials=None, @@ -766,11 +1178,14 @@ def test_local_inventory_service_client_create_channel_credentials_file(client_c ) -@pytest.mark.parametrize("request_type", [ - localinventory.ListLocalInventoriesRequest, - dict, -]) -def test_list_local_inventories(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + localinventory.ListLocalInventoriesRequest, + dict, + ], +) +def test_list_local_inventories(request_type, transport: str = "grpc"): client = LocalInventoryServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -782,11 +1197,11 @@ def test_list_local_inventories(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_local_inventories), - '__call__') as call: + type(client.transport.list_local_inventories), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = localinventory.ListLocalInventoriesResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) response = client.list_local_inventories(request) @@ -798,7 +1213,7 @@ def test_list_local_inventories(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListLocalInventoriesPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" def test_list_local_inventories_non_empty_request_with_auto_populated_field(): @@ -806,30 +1221,33 @@ def test_list_local_inventories_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = LocalInventoryServiceClient( 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 = localinventory.ListLocalInventoriesRequest( - 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_local_inventories), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.list_local_inventories), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.list_local_inventories(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == localinventory.ListLocalInventoriesRequest( - parent='parent_value', - page_token='page_token_value', + parent="parent_value", + page_token="page_token_value", ) + def test_list_local_inventories_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -844,12 +1262,19 @@ def test_list_local_inventories_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_local_inventories in client._transport._wrapped_methods + assert ( + client._transport.list_local_inventories + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_local_inventories] = 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_local_inventories + ] = mock_rpc request = {} client.list_local_inventories(request) @@ -862,8 +1287,11 @@ def test_list_local_inventories_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_local_inventories_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_list_local_inventories_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: @@ -877,12 +1305,17 @@ async def test_list_local_inventories_async_use_cached_wrapped_rpc(transport: st wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.list_local_inventories in client._client._transport._wrapped_methods + assert ( + client._client._transport.list_local_inventories + 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_local_inventories] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.list_local_inventories + ] = mock_rpc request = {} await client.list_local_inventories(request) @@ -896,8 +1329,12 @@ async def test_list_local_inventories_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_list_local_inventories_async(transport: str = 'grpc_asyncio', request_type=localinventory.ListLocalInventoriesRequest): +async def test_list_local_inventories_async( + transport: str = "grpc_asyncio", + request_type=localinventory.ListLocalInventoriesRequest, +): client = LocalInventoryServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -909,12 +1346,14 @@ async def test_list_local_inventories_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.list_local_inventories), - '__call__') as call: + type(client.transport.list_local_inventories), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(localinventory.ListLocalInventoriesResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + localinventory.ListLocalInventoriesResponse( + next_page_token="next_page_token_value", + ) + ) response = await client.list_local_inventories(request) # Establish that the underlying gRPC stub method was called. @@ -925,13 +1364,14 @@ async def test_list_local_inventories_async(transport: str = 'grpc_asyncio', req # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListLocalInventoriesAsyncPager) - 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_local_inventories_async_from_dict(): await test_list_local_inventories_async(request_type=dict) + def test_list_local_inventories_field_headers(): client = LocalInventoryServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -941,12 +1381,12 @@ def test_list_local_inventories_field_headers(): # a field header. Set these to a non-empty value. request = localinventory.ListLocalInventoriesRequest() - 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_local_inventories), - '__call__') as call: + type(client.transport.list_local_inventories), "__call__" + ) as call: call.return_value = localinventory.ListLocalInventoriesResponse() client.list_local_inventories(request) @@ -958,9 +1398,9 @@ def test_list_local_inventories_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 @@ -973,13 +1413,15 @@ async def test_list_local_inventories_field_headers_async(): # a field header. Set these to a non-empty value. request = localinventory.ListLocalInventoriesRequest() - 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_local_inventories), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.ListLocalInventoriesResponse()) + type(client.transport.list_local_inventories), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + localinventory.ListLocalInventoriesResponse() + ) await client.list_local_inventories(request) # Establish that the underlying gRPC stub method was called. @@ -990,9 +1432,9 @@ async def test_list_local_inventories_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_local_inventories_flattened(): @@ -1002,14 +1444,14 @@ def test_list_local_inventories_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__') as call: + type(client.transport.list_local_inventories), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = localinventory.ListLocalInventoriesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_local_inventories( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1017,7 +1459,7 @@ def test_list_local_inventories_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 @@ -1031,9 +1473,10 @@ def test_list_local_inventories_flattened_error(): with pytest.raises(ValueError): client.list_local_inventories( localinventory.ListLocalInventoriesRequest(), - parent='parent_value', + parent="parent_value", ) + @pytest.mark.asyncio async def test_list_local_inventories_flattened_async(): client = LocalInventoryServiceAsyncClient( @@ -1042,16 +1485,18 @@ async def test_list_local_inventories_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__') as call: + type(client.transport.list_local_inventories), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = localinventory.ListLocalInventoriesResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.ListLocalInventoriesResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + localinventory.ListLocalInventoriesResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_local_inventories( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1059,9 +1504,10 @@ async def test_list_local_inventories_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_local_inventories_flattened_error_async(): client = LocalInventoryServiceAsyncClient( @@ -1073,7 +1519,7 @@ async def test_list_local_inventories_flattened_error_async(): with pytest.raises(ValueError): await client.list_local_inventories( localinventory.ListLocalInventoriesRequest(), - parent='parent_value', + parent="parent_value", ) @@ -1085,8 +1531,8 @@ def test_list_local_inventories_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_local_inventories), - '__call__') as call: + type(client.transport.list_local_inventories), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( localinventory.ListLocalInventoriesResponse( @@ -1095,17 +1541,17 @@ def test_list_local_inventories_pager(transport_name: str = "grpc"): localinventory.LocalInventory(), localinventory.LocalInventory(), ], - next_page_token='abc', + next_page_token="abc", ), localinventory.ListLocalInventoriesResponse( local_inventories=[], - next_page_token='def', + next_page_token="def", ), localinventory.ListLocalInventoriesResponse( local_inventories=[ localinventory.LocalInventory(), ], - next_page_token='ghi', + next_page_token="ghi", ), localinventory.ListLocalInventoriesResponse( local_inventories=[ @@ -1120,9 +1566,7 @@ def test_list_local_inventories_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_local_inventories(request={}, retry=retry, timeout=timeout) @@ -1132,8 +1576,9 @@ def test_list_local_inventories_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, localinventory.LocalInventory) - for i in results) + assert all(isinstance(i, localinventory.LocalInventory) for i in results) + + def test_list_local_inventories_pages(transport_name: str = "grpc"): client = LocalInventoryServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1142,8 +1587,8 @@ def test_list_local_inventories_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_local_inventories), - '__call__') as call: + type(client.transport.list_local_inventories), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( localinventory.ListLocalInventoriesResponse( @@ -1152,17 +1597,17 @@ def test_list_local_inventories_pages(transport_name: str = "grpc"): localinventory.LocalInventory(), localinventory.LocalInventory(), ], - next_page_token='abc', + next_page_token="abc", ), localinventory.ListLocalInventoriesResponse( local_inventories=[], - next_page_token='def', + next_page_token="def", ), localinventory.ListLocalInventoriesResponse( local_inventories=[ localinventory.LocalInventory(), ], - next_page_token='ghi', + next_page_token="ghi", ), localinventory.ListLocalInventoriesResponse( local_inventories=[ @@ -1173,9 +1618,10 @@ def test_list_local_inventories_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_local_inventories(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_local_inventories_async_pager(): client = LocalInventoryServiceAsyncClient( @@ -1184,8 +1630,10 @@ async def test_list_local_inventories_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_local_inventories), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( localinventory.ListLocalInventoriesResponse( @@ -1194,17 +1642,17 @@ async def test_list_local_inventories_async_pager(): localinventory.LocalInventory(), localinventory.LocalInventory(), ], - next_page_token='abc', + next_page_token="abc", ), localinventory.ListLocalInventoriesResponse( local_inventories=[], - next_page_token='def', + next_page_token="def", ), localinventory.ListLocalInventoriesResponse( local_inventories=[ localinventory.LocalInventory(), ], - next_page_token='ghi', + next_page_token="ghi", ), localinventory.ListLocalInventoriesResponse( local_inventories=[ @@ -1214,15 +1662,16 @@ async def test_list_local_inventories_async_pager(): ), RuntimeError, ) - async_pager = await client.list_local_inventories(request={},) - assert async_pager.next_page_token == 'abc' + async_pager = await client.list_local_inventories( + 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, localinventory.LocalInventory) - for i in responses) + assert all(isinstance(i, localinventory.LocalInventory) for i in responses) @pytest.mark.asyncio @@ -1233,8 +1682,10 @@ async def test_list_local_inventories_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_local_inventories), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( localinventory.ListLocalInventoriesResponse( @@ -1243,17 +1694,17 @@ async def test_list_local_inventories_async_pages(): localinventory.LocalInventory(), localinventory.LocalInventory(), ], - next_page_token='abc', + next_page_token="abc", ), localinventory.ListLocalInventoriesResponse( local_inventories=[], - next_page_token='def', + next_page_token="def", ), localinventory.ListLocalInventoriesResponse( local_inventories=[ localinventory.LocalInventory(), ], - next_page_token='ghi', + next_page_token="ghi", ), localinventory.ListLocalInventoriesResponse( local_inventories=[ @@ -1266,18 +1717,22 @@ async def test_list_local_inventories_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_local_inventories(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", [ - localinventory.InsertLocalInventoryRequest, - dict, -]) -def test_insert_local_inventory(request_type, transport: str = 'grpc'): + +@pytest.mark.parametrize( + "request_type", + [ + localinventory.InsertLocalInventoryRequest, + dict, + ], +) +def test_insert_local_inventory(request_type, transport: str = "grpc"): client = LocalInventoryServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1289,13 +1744,13 @@ def test_insert_local_inventory(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.insert_local_inventory), - '__call__') as call: + type(client.transport.insert_local_inventory), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = localinventory.LocalInventory( - name='name_value', + name="name_value", account=749, - store_code='store_code_value', + store_code="store_code_value", ) response = client.insert_local_inventory(request) @@ -1307,9 +1762,9 @@ def test_insert_local_inventory(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, localinventory.LocalInventory) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.account == 749 - assert response.store_code == 'store_code_value' + assert response.store_code == "store_code_value" def test_insert_local_inventory_non_empty_request_with_auto_populated_field(): @@ -1317,28 +1772,31 @@ def test_insert_local_inventory_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = LocalInventoryServiceClient( 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 = localinventory.InsertLocalInventoryRequest( - 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.insert_local_inventory), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.insert_local_inventory), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.insert_local_inventory(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == localinventory.InsertLocalInventoryRequest( - parent='parent_value', + parent="parent_value", ) + def test_insert_local_inventory_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1353,12 +1811,19 @@ def test_insert_local_inventory_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.insert_local_inventory in client._transport._wrapped_methods + assert ( + client._transport.insert_local_inventory + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.insert_local_inventory] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.insert_local_inventory + ] = mock_rpc request = {} client.insert_local_inventory(request) @@ -1371,8 +1836,11 @@ def test_insert_local_inventory_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_insert_local_inventory_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_insert_local_inventory_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: @@ -1386,12 +1854,17 @@ async def test_insert_local_inventory_async_use_cached_wrapped_rpc(transport: st wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.insert_local_inventory in client._client._transport._wrapped_methods + assert ( + client._client._transport.insert_local_inventory + 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.insert_local_inventory] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.insert_local_inventory + ] = mock_rpc request = {} await client.insert_local_inventory(request) @@ -1405,8 +1878,12 @@ async def test_insert_local_inventory_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_insert_local_inventory_async(transport: str = 'grpc_asyncio', request_type=localinventory.InsertLocalInventoryRequest): +async def test_insert_local_inventory_async( + transport: str = "grpc_asyncio", + request_type=localinventory.InsertLocalInventoryRequest, +): client = LocalInventoryServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1418,14 +1895,16 @@ async def test_insert_local_inventory_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.insert_local_inventory), - '__call__') as call: + type(client.transport.insert_local_inventory), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(localinventory.LocalInventory( - name='name_value', - account=749, - store_code='store_code_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + localinventory.LocalInventory( + name="name_value", + account=749, + store_code="store_code_value", + ) + ) response = await client.insert_local_inventory(request) # Establish that the underlying gRPC stub method was called. @@ -1436,15 +1915,16 @@ async def test_insert_local_inventory_async(transport: str = 'grpc_asyncio', req # Establish that the response is the type that we expect. assert isinstance(response, localinventory.LocalInventory) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.account == 749 - assert response.store_code == 'store_code_value' + assert response.store_code == "store_code_value" @pytest.mark.asyncio async def test_insert_local_inventory_async_from_dict(): await test_insert_local_inventory_async(request_type=dict) + def test_insert_local_inventory_field_headers(): client = LocalInventoryServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1454,12 +1934,12 @@ def test_insert_local_inventory_field_headers(): # a field header. Set these to a non-empty value. request = localinventory.InsertLocalInventoryRequest() - 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.insert_local_inventory), - '__call__') as call: + type(client.transport.insert_local_inventory), "__call__" + ) as call: call.return_value = localinventory.LocalInventory() client.insert_local_inventory(request) @@ -1471,9 +1951,9 @@ def test_insert_local_inventory_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 @@ -1486,13 +1966,15 @@ async def test_insert_local_inventory_field_headers_async(): # a field header. Set these to a non-empty value. request = localinventory.InsertLocalInventoryRequest() - 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.insert_local_inventory), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.LocalInventory()) + type(client.transport.insert_local_inventory), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + localinventory.LocalInventory() + ) await client.insert_local_inventory(request) # Establish that the underlying gRPC stub method was called. @@ -1503,16 +1985,19 @@ async def test_insert_local_inventory_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"] -@pytest.mark.parametrize("request_type", [ - localinventory.DeleteLocalInventoryRequest, - dict, -]) -def test_delete_local_inventory(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + localinventory.DeleteLocalInventoryRequest, + dict, + ], +) +def test_delete_local_inventory(request_type, transport: str = "grpc"): client = LocalInventoryServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1524,8 +2009,8 @@ def test_delete_local_inventory(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_local_inventory), - '__call__') as call: + type(client.transport.delete_local_inventory), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = None response = client.delete_local_inventory(request) @@ -1545,28 +2030,31 @@ def test_delete_local_inventory_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = LocalInventoryServiceClient( 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 = localinventory.DeleteLocalInventoryRequest( - 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_local_inventory), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.delete_local_inventory), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.delete_local_inventory(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == localinventory.DeleteLocalInventoryRequest( - name='name_value', + name="name_value", ) + def test_delete_local_inventory_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1581,12 +2069,19 @@ def test_delete_local_inventory_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_local_inventory in client._transport._wrapped_methods + assert ( + client._transport.delete_local_inventory + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_local_inventory] = 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_local_inventory + ] = mock_rpc request = {} client.delete_local_inventory(request) @@ -1599,8 +2094,11 @@ def test_delete_local_inventory_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_delete_local_inventory_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_delete_local_inventory_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: @@ -1614,12 +2112,17 @@ async def test_delete_local_inventory_async_use_cached_wrapped_rpc(transport: st wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.delete_local_inventory in client._client._transport._wrapped_methods + assert ( + client._client._transport.delete_local_inventory + 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_local_inventory] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.delete_local_inventory + ] = mock_rpc request = {} await client.delete_local_inventory(request) @@ -1633,8 +2136,12 @@ async def test_delete_local_inventory_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_local_inventory_async(transport: str = 'grpc_asyncio', request_type=localinventory.DeleteLocalInventoryRequest): +async def test_delete_local_inventory_async( + transport: str = "grpc_asyncio", + request_type=localinventory.DeleteLocalInventoryRequest, +): client = LocalInventoryServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1646,8 +2153,8 @@ async def test_delete_local_inventory_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_local_inventory), - '__call__') as call: + type(client.transport.delete_local_inventory), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.delete_local_inventory(request) @@ -1666,6 +2173,7 @@ async def test_delete_local_inventory_async(transport: str = 'grpc_asyncio', req async def test_delete_local_inventory_async_from_dict(): await test_delete_local_inventory_async(request_type=dict) + def test_delete_local_inventory_field_headers(): client = LocalInventoryServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1675,12 +2183,12 @@ def test_delete_local_inventory_field_headers(): # a field header. Set these to a non-empty value. request = localinventory.DeleteLocalInventoryRequest() - 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_local_inventory), - '__call__') as call: + type(client.transport.delete_local_inventory), "__call__" + ) as call: call.return_value = None client.delete_local_inventory(request) @@ -1692,9 +2200,9 @@ def test_delete_local_inventory_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 @@ -1707,12 +2215,12 @@ async def test_delete_local_inventory_field_headers_async(): # a field header. Set these to a non-empty value. request = localinventory.DeleteLocalInventoryRequest() - 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_local_inventory), - '__call__') as call: + type(client.transport.delete_local_inventory), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_local_inventory(request) @@ -1724,9 +2232,9 @@ async def test_delete_local_inventory_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_local_inventory_flattened(): @@ -1736,14 +2244,14 @@ def test_delete_local_inventory_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_local_inventory), - '__call__') as call: + type(client.transport.delete_local_inventory), "__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_local_inventory( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1751,7 +2259,7 @@ def test_delete_local_inventory_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 @@ -1765,9 +2273,10 @@ def test_delete_local_inventory_flattened_error(): with pytest.raises(ValueError): client.delete_local_inventory( localinventory.DeleteLocalInventoryRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_delete_local_inventory_flattened_async(): client = LocalInventoryServiceAsyncClient( @@ -1776,8 +2285,8 @@ async def test_delete_local_inventory_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_local_inventory), - '__call__') as call: + type(client.transport.delete_local_inventory), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = None @@ -1785,7 +2294,7 @@ async def test_delete_local_inventory_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.delete_local_inventory( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1793,9 +2302,10 @@ async def test_delete_local_inventory_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_local_inventory_flattened_error_async(): client = LocalInventoryServiceAsyncClient( @@ -1807,7 +2317,7 @@ async def test_delete_local_inventory_flattened_error_async(): with pytest.raises(ValueError): await client.delete_local_inventory( localinventory.DeleteLocalInventoryRequest(), - name='name_value', + name="name_value", ) @@ -1825,12 +2335,19 @@ def test_list_local_inventories_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_local_inventories in client._transport._wrapped_methods + assert ( + client._transport.list_local_inventories + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_local_inventories] = 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_local_inventories + ] = mock_rpc request = {} client.list_local_inventories(request) @@ -1845,57 +2362,67 @@ def test_list_local_inventories_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_list_local_inventories_rest_required_fields(request_type=localinventory.ListLocalInventoriesRequest): +def test_list_local_inventories_rest_required_fields( + request_type=localinventory.ListLocalInventoriesRequest, +): transport_class = transports.LocalInventoryServiceRestTransport 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_local_inventories._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_local_inventories._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_local_inventories._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_local_inventories._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 = LocalInventoryServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = localinventory.ListLocalInventoriesResponse() # 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 @@ -1906,24 +2433,32 @@ def test_list_local_inventories_rest_required_fields(request_type=localinventory return_value = localinventory.ListLocalInventoriesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_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_local_inventories(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_local_inventories_rest_unset_required_fields(): - transport = transports.LocalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.LocalInventoryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.list_local_inventories._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_local_inventories_rest_flattened(): @@ -1933,16 +2468,16 @@ def test_list_local_inventories_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 = localinventory.ListLocalInventoriesResponse() # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1/products/sample2'} + sample_request = {"parent": "accounts/sample1/products/sample2"} # get truthy value for each flattened field mock_args = dict( - parent='parent_value', + parent="parent_value", ) mock_args.update(sample_request) @@ -1952,7 +2487,7 @@ def test_list_local_inventories_rest_flattened(): # Convert return value to protobuf type return_value = localinventory.ListLocalInventoriesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -1962,10 +2497,14 @@ def test_list_local_inventories_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/inventories/v1/{parent=accounts/*/products/*}/localInventories" % client.transport._host, args[1]) + assert path_template.validate( + "%s/inventories/v1/{parent=accounts/*/products/*}/localInventories" + % client.transport._host, + args[1], + ) -def test_list_local_inventories_rest_flattened_error(transport: str = 'rest'): +def test_list_local_inventories_rest_flattened_error(transport: str = "rest"): client = LocalInventoryServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1976,20 +2515,20 @@ def test_list_local_inventories_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.list_local_inventories( localinventory.ListLocalInventoriesRequest(), - parent='parent_value', + parent="parent_value", ) -def test_list_local_inventories_rest_pager(transport: str = 'rest'): +def test_list_local_inventories_rest_pager(transport: str = "rest"): client = LocalInventoryServiceClient( 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 = ( localinventory.ListLocalInventoriesResponse( @@ -1998,17 +2537,17 @@ def test_list_local_inventories_rest_pager(transport: str = 'rest'): localinventory.LocalInventory(), localinventory.LocalInventory(), ], - next_page_token='abc', + next_page_token="abc", ), localinventory.ListLocalInventoriesResponse( local_inventories=[], - next_page_token='def', + next_page_token="def", ), localinventory.ListLocalInventoriesResponse( local_inventories=[ localinventory.LocalInventory(), ], - next_page_token='ghi', + next_page_token="ghi", ), localinventory.ListLocalInventoriesResponse( local_inventories=[ @@ -2021,24 +2560,25 @@ def test_list_local_inventories_rest_pager(transport: str = 'rest'): response = response + response # Wrap the values into proper Response objs - response = tuple(localinventory.ListLocalInventoriesResponse.to_json(x) for x in response) + response = tuple( + localinventory.ListLocalInventoriesResponse.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': 'accounts/sample1/products/sample2'} + sample_request = {"parent": "accounts/sample1/products/sample2"} pager = client.list_local_inventories(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, localinventory.LocalInventory) - for i in results) + assert all(isinstance(i, localinventory.LocalInventory) for i in results) pages = list(client.list_local_inventories(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 @@ -2056,12 +2596,19 @@ def test_insert_local_inventory_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.insert_local_inventory in client._transport._wrapped_methods + assert ( + client._transport.insert_local_inventory + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.insert_local_inventory] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.insert_local_inventory + ] = mock_rpc request = {} client.insert_local_inventory(request) @@ -2076,57 +2623,62 @@ def test_insert_local_inventory_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_insert_local_inventory_rest_required_fields(request_type=localinventory.InsertLocalInventoryRequest): +def test_insert_local_inventory_rest_required_fields( + request_type=localinventory.InsertLocalInventoryRequest, +): transport_class = transports.LocalInventoryServiceRestTransport 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()).insert_local_inventory._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).insert_local_inventory._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()).insert_local_inventory._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).insert_local_inventory._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 = LocalInventoryServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = localinventory.LocalInventory() # 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() @@ -2136,24 +2688,32 @@ def test_insert_local_inventory_rest_required_fields(request_type=localinventory return_value = localinventory.LocalInventory.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.insert_local_inventory(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_insert_local_inventory_rest_unset_required_fields(): - transport = transports.LocalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.LocalInventoryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.insert_local_inventory._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "localInventory", ))) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "localInventory", + ) + ) + ) def test_delete_local_inventory_rest_use_cached_wrapped_rpc(): @@ -2170,12 +2730,19 @@ def test_delete_local_inventory_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_local_inventory in client._transport._wrapped_methods + assert ( + client._transport.delete_local_inventory + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_local_inventory] = 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_local_inventory + ] = mock_rpc request = {} client.delete_local_inventory(request) @@ -2190,80 +2757,85 @@ def test_delete_local_inventory_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_delete_local_inventory_rest_required_fields(request_type=localinventory.DeleteLocalInventoryRequest): +def test_delete_local_inventory_rest_required_fields( + request_type=localinventory.DeleteLocalInventoryRequest, +): transport_class = transports.LocalInventoryServiceRestTransport 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_local_inventory._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_local_inventory._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_local_inventory._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_local_inventory._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 = LocalInventoryServiceClient( 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_local_inventory(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_local_inventory_rest_unset_required_fields(): - transport = transports.LocalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.LocalInventoryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.delete_local_inventory._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_delete_local_inventory_rest_flattened(): @@ -2273,24 +2845,26 @@ def test_delete_local_inventory_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': 'accounts/sample1/products/sample2/localInventories/sample3'} + sample_request = { + "name": "accounts/sample1/products/sample2/localInventories/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"} @@ -2300,10 +2874,14 @@ def test_delete_local_inventory_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/inventories/v1/{name=accounts/*/products/*/localInventories/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/inventories/v1/{name=accounts/*/products/*/localInventories/*}" + % client.transport._host, + args[1], + ) -def test_delete_local_inventory_rest_flattened_error(transport: str = 'rest'): +def test_delete_local_inventory_rest_flattened_error(transport: str = "rest"): client = LocalInventoryServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2314,7 +2892,7 @@ def test_delete_local_inventory_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.delete_local_inventory( localinventory.DeleteLocalInventoryRequest(), - name='name_value', + name="name_value", ) @@ -2356,8 +2934,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = LocalInventoryServiceClient( - 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. @@ -2379,6 +2956,7 @@ def test_transport_instance(): client = LocalInventoryServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.LocalInventoryServiceGrpcTransport( @@ -2393,18 +2971,23 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.LocalInventoryServiceGrpcTransport, - transports.LocalInventoryServiceGrpcAsyncIOTransport, - transports.LocalInventoryServiceRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.LocalInventoryServiceGrpcTransport, + transports.LocalInventoryServiceGrpcAsyncIOTransport, + transports.LocalInventoryServiceRestTransport, + ], +) 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 = LocalInventoryServiceClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -2414,8 +2997,7 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) assert client is not None @@ -2430,8 +3012,8 @@ def test_list_local_inventories_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__') as call: + type(client.transport.list_local_inventories), "__call__" + ) as call: call.return_value = localinventory.ListLocalInventoriesResponse() client.list_local_inventories(request=None) @@ -2453,8 +3035,8 @@ def test_insert_local_inventory_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.insert_local_inventory), - '__call__') as call: + type(client.transport.insert_local_inventory), "__call__" + ) as call: call.return_value = localinventory.LocalInventory() client.insert_local_inventory(request=None) @@ -2476,8 +3058,8 @@ def test_delete_local_inventory_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_local_inventory), - '__call__') as call: + type(client.transport.delete_local_inventory), "__call__" + ) as call: call.return_value = None client.delete_local_inventory(request=None) @@ -2498,8 +3080,7 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = LocalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) assert client is not None @@ -2515,12 +3096,14 @@ async def test_list_local_inventories_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__') as call: + type(client.transport.list_local_inventories), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.ListLocalInventoriesResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + localinventory.ListLocalInventoriesResponse( + next_page_token="next_page_token_value", + ) + ) await client.list_local_inventories(request=None) # Establish that the underlying stub method was called. @@ -2542,14 +3125,16 @@ async def test_insert_local_inventory_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.insert_local_inventory), - '__call__') as call: + type(client.transport.insert_local_inventory), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(localinventory.LocalInventory( - name='name_value', - account=749, - store_code='store_code_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + localinventory.LocalInventory( + name="name_value", + account=749, + store_code="store_code_value", + ) + ) await client.insert_local_inventory(request=None) # Establish that the underlying stub method was called. @@ -2571,8 +3156,8 @@ async def test_delete_local_inventory_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_local_inventory), - '__call__') as call: + type(client.transport.delete_local_inventory), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_local_inventory(request=None) @@ -2592,20 +3177,23 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_list_local_inventories_rest_bad_request(request_type=localinventory.ListLocalInventoriesRequest): +def test_list_local_inventories_rest_bad_request( + request_type=localinventory.ListLocalInventoriesRequest, +): client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/products/sample2'} + request_init = {"parent": "accounts/sample1/products/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() @@ -2614,25 +3202,27 @@ def test_list_local_inventories_rest_bad_request(request_type=localinventory.Lis client.list_local_inventories(request) -@pytest.mark.parametrize("request_type", [ - localinventory.ListLocalInventoriesRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + localinventory.ListLocalInventoriesRequest, + dict, + ], +) def test_list_local_inventories_rest_call_success(request_type): client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/products/sample2'} + request_init = {"parent": "accounts/sample1/products/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 = localinventory.ListLocalInventoriesResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -2642,33 +3232,44 @@ def test_list_local_inventories_rest_call_success(request_type): # Convert return value to protobuf type return_value = localinventory.ListLocalInventoriesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_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_local_inventories(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListLocalInventoriesPager) - 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_local_inventories_rest_interceptors(null_interceptor): transport = transports.LocalInventoryServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.LocalInventoryServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.LocalInventoryServiceRestInterceptor(), + ) client = LocalInventoryServiceClient(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.LocalInventoryServiceRestInterceptor, "post_list_local_inventories") as post, \ - mock.patch.object(transports.LocalInventoryServiceRestInterceptor, "post_list_local_inventories_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.LocalInventoryServiceRestInterceptor, "pre_list_local_inventories") 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.LocalInventoryServiceRestInterceptor, "post_list_local_inventories" + ) as post, mock.patch.object( + transports.LocalInventoryServiceRestInterceptor, + "post_list_local_inventories_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.LocalInventoryServiceRestInterceptor, "pre_list_local_inventories" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = localinventory.ListLocalInventoriesRequest.pb(localinventory.ListLocalInventoriesRequest()) + pb_message = localinventory.ListLocalInventoriesRequest.pb( + localinventory.ListLocalInventoriesRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2679,39 +3280,53 @@ def test_list_local_inventories_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 = localinventory.ListLocalInventoriesResponse.to_json(localinventory.ListLocalInventoriesResponse()) + return_value = localinventory.ListLocalInventoriesResponse.to_json( + localinventory.ListLocalInventoriesResponse() + ) req.return_value.content = return_value request = localinventory.ListLocalInventoriesRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = localinventory.ListLocalInventoriesResponse() - post_with_metadata.return_value = localinventory.ListLocalInventoriesResponse(), metadata + post_with_metadata.return_value = ( + localinventory.ListLocalInventoriesResponse(), + metadata, + ) - client.list_local_inventories(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.list_local_inventories( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_insert_local_inventory_rest_bad_request(request_type=localinventory.InsertLocalInventoryRequest): +def test_insert_local_inventory_rest_bad_request( + request_type=localinventory.InsertLocalInventoryRequest, +): client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/products/sample2'} + request_init = {"parent": "accounts/sample1/products/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() @@ -2720,25 +3335,46 @@ def test_insert_local_inventory_rest_bad_request(request_type=localinventory.Ins client.insert_local_inventory(request) -@pytest.mark.parametrize("request_type", [ - localinventory.InsertLocalInventoryRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + localinventory.InsertLocalInventoryRequest, + dict, + ], +) def test_insert_local_inventory_rest_call_success(request_type): client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/products/sample2'} - request_init["local_inventory"] = {'name': 'name_value', 'account': 749, 'store_code': 'store_code_value', 'local_inventory_attributes': {'price': {'amount_micros': 1408, 'currency_code': 'currency_code_value'}, 'sale_price': {}, 'sale_price_effective_date': {'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}}, 'availability': 1, 'quantity': 895, 'pickup_method': 1, 'pickup_sla': 1, 'instore_product_location': 'instore_product_location_value'}} + request_init = {"parent": "accounts/sample1/products/sample2"} + request_init["local_inventory"] = { + "name": "name_value", + "account": 749, + "store_code": "store_code_value", + "local_inventory_attributes": { + "price": {"amount_micros": 1408, "currency_code": "currency_code_value"}, + "sale_price": {}, + "sale_price_effective_date": { + "start_time": {"seconds": 751, "nanos": 543}, + "end_time": {}, + }, + "availability": 1, + "quantity": 895, + "pickup_method": 1, + "pickup_sla": 1, + "instore_product_location": "instore_product_location_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 # Determine if the message type is proto-plus or protobuf - test_field = localinventory.InsertLocalInventoryRequest.meta.fields["local_inventory"] + test_field = localinventory.InsertLocalInventoryRequest.meta.fields[ + "local_inventory" + ] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -2752,7 +3388,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 @@ -2766,7 +3402,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["local_inventory"].items(): # pragma: NO COVER + for field, value in request_init["local_inventory"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -2781,12 +3417,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") @@ -2799,12 +3439,12 @@ 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 = localinventory.LocalInventory( - name='name_value', - account=749, - store_code='store_code_value', + name="name_value", + account=749, + store_code="store_code_value", ) # Wrap the value into a proper Response obj @@ -2814,35 +3454,46 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = localinventory.LocalInventory.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.insert_local_inventory(request) # Establish that the response is the type that we expect. assert isinstance(response, localinventory.LocalInventory) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.account == 749 - assert response.store_code == 'store_code_value' + assert response.store_code == "store_code_value" @pytest.mark.parametrize("null_interceptor", [True, False]) def test_insert_local_inventory_rest_interceptors(null_interceptor): transport = transports.LocalInventoryServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.LocalInventoryServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.LocalInventoryServiceRestInterceptor(), + ) client = LocalInventoryServiceClient(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.LocalInventoryServiceRestInterceptor, "post_insert_local_inventory") as post, \ - mock.patch.object(transports.LocalInventoryServiceRestInterceptor, "post_insert_local_inventory_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.LocalInventoryServiceRestInterceptor, "pre_insert_local_inventory") 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.LocalInventoryServiceRestInterceptor, "post_insert_local_inventory" + ) as post, mock.patch.object( + transports.LocalInventoryServiceRestInterceptor, + "post_insert_local_inventory_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.LocalInventoryServiceRestInterceptor, "pre_insert_local_inventory" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = localinventory.InsertLocalInventoryRequest.pb(localinventory.InsertLocalInventoryRequest()) + pb_message = localinventory.InsertLocalInventoryRequest.pb( + localinventory.InsertLocalInventoryRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2853,11 +3504,13 @@ def test_insert_local_inventory_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 = localinventory.LocalInventory.to_json(localinventory.LocalInventory()) + return_value = localinventory.LocalInventory.to_json( + localinventory.LocalInventory() + ) req.return_value.content = return_value request = localinventory.InsertLocalInventoryRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -2865,27 +3518,38 @@ def test_insert_local_inventory_rest_interceptors(null_interceptor): post.return_value = localinventory.LocalInventory() post_with_metadata.return_value = localinventory.LocalInventory(), metadata - client.insert_local_inventory(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.insert_local_inventory( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_delete_local_inventory_rest_bad_request(request_type=localinventory.DeleteLocalInventoryRequest): +def test_delete_local_inventory_rest_bad_request( + request_type=localinventory.DeleteLocalInventoryRequest, +): client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/products/sample2/localInventories/sample3'} + request_init = { + "name": "accounts/sample1/products/sample2/localInventories/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() @@ -2894,30 +3558,34 @@ def test_delete_local_inventory_rest_bad_request(request_type=localinventory.Del client.delete_local_inventory(request) -@pytest.mark.parametrize("request_type", [ - localinventory.DeleteLocalInventoryRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + localinventory.DeleteLocalInventoryRequest, + dict, + ], +) def test_delete_local_inventory_rest_call_success(request_type): client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/products/sample2/localInventories/sample3'} + request_init = { + "name": "accounts/sample1/products/sample2/localInventories/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_local_inventory(request) @@ -2930,15 +3598,23 @@ def test_delete_local_inventory_rest_call_success(request_type): def test_delete_local_inventory_rest_interceptors(null_interceptor): transport = transports.LocalInventoryServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.LocalInventoryServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.LocalInventoryServiceRestInterceptor(), + ) client = LocalInventoryServiceClient(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.LocalInventoryServiceRestInterceptor, "pre_delete_local_inventory") 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.LocalInventoryServiceRestInterceptor, "pre_delete_local_inventory" + ) as pre: pre.assert_not_called() - pb_message = localinventory.DeleteLocalInventoryRequest.pb(localinventory.DeleteLocalInventoryRequest()) + pb_message = localinventory.DeleteLocalInventoryRequest.pb( + localinventory.DeleteLocalInventoryRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2951,20 +3627,26 @@ def test_delete_local_inventory_rest_interceptors(null_interceptor): req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = localinventory.DeleteLocalInventoryRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - client.delete_local_inventory(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.delete_local_inventory( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() + def test_initialize_client_w_rest(): client = LocalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None @@ -2979,8 +3661,8 @@ def test_list_local_inventories_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_local_inventories), - '__call__') as call: + type(client.transport.list_local_inventories), "__call__" + ) as call: client.list_local_inventories(request=None) # Establish that the underlying stub method was called. @@ -3001,8 +3683,8 @@ def test_insert_local_inventory_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.insert_local_inventory), - '__call__') as call: + type(client.transport.insert_local_inventory), "__call__" + ) as call: client.insert_local_inventory(request=None) # Establish that the underlying stub method was called. @@ -3023,8 +3705,8 @@ def test_delete_local_inventory_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_local_inventory), - '__call__') as call: + type(client.transport.delete_local_inventory), "__call__" + ) as call: client.delete_local_inventory(request=None) # Establish that the underlying stub method was called. @@ -3045,18 +3727,21 @@ def test_transport_grpc_default(): transports.LocalInventoryServiceGrpcTransport, ) + def test_local_inventory_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.LocalInventoryServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_local_inventory_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.shopping.merchant_inventories_v1.services.local_inventory_service.transports.LocalInventoryServiceTransport.__init__') as Transport: + with mock.patch( + "google.shopping.merchant_inventories_v1.services.local_inventory_service.transports.LocalInventoryServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.LocalInventoryServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -3065,9 +3750,9 @@ def test_local_inventory_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'list_local_inventories', - 'insert_local_inventory', - 'delete_local_inventory', + "list_local_inventories", + "insert_local_inventory", + "delete_local_inventory", ) for method in methods: with pytest.raises(NotImplementedError): @@ -3078,7 +3763,7 @@ def test_local_inventory_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -3087,25 +3772,30 @@ def test_local_inventory_service_base_transport(): def test_local_inventory_service_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.shopping.merchant_inventories_v1.services.local_inventory_service.transports.LocalInventoryServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.shopping.merchant_inventories_v1.services.local_inventory_service.transports.LocalInventoryServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.LocalInventoryServiceTransport( 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/content', -), + default_scopes=("https://www.googleapis.com/auth/content",), quota_project_id="octopus", ) def test_local_inventory_service_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.shopping.merchant_inventories_v1.services.local_inventory_service.transports.LocalInventoryServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.shopping.merchant_inventories_v1.services.local_inventory_service.transports.LocalInventoryServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.LocalInventoryServiceTransport() @@ -3114,14 +3804,12 @@ def test_local_inventory_service_base_transport_with_adc(): def test_local_inventory_service_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) LocalInventoryServiceClient() adc.assert_called_once_with( scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/content', -), + default_scopes=("https://www.googleapis.com/auth/content",), quota_project_id=None, ) @@ -3136,12 +3824,12 @@ def test_local_inventory_service_auth_adc(): def test_local_inventory_service_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: + 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/content',), + default_scopes=("https://www.googleapis.com/auth/content",), quota_project_id="octopus", ) @@ -3155,48 +3843,47 @@ def test_local_inventory_service_transport_auth_adc(transport_class): ], ) def test_local_inventory_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] + 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.LocalInventoryServiceGrpcTransport, grpc_helpers), - (transports.LocalInventoryServiceGrpcAsyncIOTransport, grpc_helpers_async) + (transports.LocalInventoryServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -def test_local_inventory_service_transport_create_channel(transport_class, grpc_helpers): +def test_local_inventory_service_transport_create_channel( + transport_class, grpc_helpers +): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + 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( "merchantapi.googleapis.com:443", credentials=creds, credentials_file=None, quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/content', -), + default_scopes=("https://www.googleapis.com/auth/content",), scopes=["1", "2"], default_host="merchantapi.googleapis.com", ssl_credentials=None, @@ -3207,9 +3894,15 @@ def test_local_inventory_service_transport_create_channel(transport_class, grpc_ ) -@pytest.mark.parametrize("transport_class", [transports.LocalInventoryServiceGrpcTransport, transports.LocalInventoryServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.LocalInventoryServiceGrpcTransport, + transports.LocalInventoryServiceGrpcAsyncIOTransport, + ], +) def test_local_inventory_service_grpc_transport_client_cert_source_for_mtls( - transport_class + transport_class, ): cred = ga_credentials.AnonymousCredentials() @@ -3219,7 +3912,7 @@ def test_local_inventory_service_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", @@ -3240,61 +3933,77 @@ def test_local_inventory_service_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_local_inventory_service_http_transport_client_cert_source_for_mtls(): cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.LocalInventoryServiceRestTransport ( - 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.LocalInventoryServiceRestTransport( + 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_local_inventory_service_host_no_port(transport_name): client = LocalInventoryServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='merchantapi.googleapis.com'), - transport=transport_name, + client_options=client_options.ClientOptions( + api_endpoint="merchantapi.googleapis.com" + ), + transport=transport_name, ) assert client.transport._host == ( - 'merchantapi.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://merchantapi.googleapis.com' + "merchantapi.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://merchantapi.googleapis.com" ) -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) def test_local_inventory_service_host_with_port(transport_name): client = LocalInventoryServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='merchantapi.googleapis.com:8000'), + client_options=client_options.ClientOptions( + api_endpoint="merchantapi.googleapis.com:8000" + ), transport=transport_name, ) assert client.transport._host == ( - 'merchantapi.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://merchantapi.googleapis.com:8000' + "merchantapi.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://merchantapi.googleapis.com:8000" ) -@pytest.mark.parametrize("transport_name", [ - "rest", -]) + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) def test_local_inventory_service_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -3315,8 +4024,10 @@ def test_local_inventory_service_client_transport_session_collision(transport_na session1 = client1.transport.delete_local_inventory._session session2 = client2.transport.delete_local_inventory._session assert session1 != session2 + + def test_local_inventory_service_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.LocalInventoryServiceGrpcTransport( @@ -3329,7 +4040,7 @@ def test_local_inventory_service_grpc_transport_channel(): def test_local_inventory_service_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.LocalInventoryServiceGrpcAsyncIOTransport( @@ -3343,12 +4054,22 @@ def test_local_inventory_service_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.parametrize("transport_class", [transports.LocalInventoryServiceGrpcTransport, transports.LocalInventoryServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.LocalInventoryServiceGrpcTransport, + transports.LocalInventoryServiceGrpcAsyncIOTransport, + ], +) def test_local_inventory_service_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 @@ -3357,7 +4078,7 @@ def test_local_inventory_service_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", @@ -3387,17 +4108,23 @@ def test_local_inventory_service_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.LocalInventoryServiceGrpcTransport, transports.LocalInventoryServiceGrpcAsyncIOTransport]) -def test_local_inventory_service_transport_channel_mtls_with_adc( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.LocalInventoryServiceGrpcTransport, + transports.LocalInventoryServiceGrpcAsyncIOTransport, + ], +) +def test_local_inventory_service_transport_channel_mtls_with_adc(transport_class): mock_ssl_cred = mock.Mock() with mock.patch.multiple( "google.auth.transport.grpc.SslCredentials", __init__=mock.Mock(return_value=None), ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + 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() @@ -3429,8 +4156,16 @@ def test_local_inventory_path(): account = "squid" product = "clam" store_code = "whelk" - expected = "accounts/{account}/products/{product}/localInventories/{store_code}".format(account=account, product=product, store_code=store_code, ) - actual = LocalInventoryServiceClient.local_inventory_path(account, product, store_code) + expected = ( + "accounts/{account}/products/{product}/localInventories/{store_code}".format( + account=account, + product=product, + store_code=store_code, + ) + ) + actual = LocalInventoryServiceClient.local_inventory_path( + account, product, store_code + ) assert expected == actual @@ -3446,9 +4181,12 @@ def test_parse_local_inventory_path(): actual = LocalInventoryServiceClient.parse_local_inventory_path(path) assert expected == actual + def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) actual = LocalInventoryServiceClient.common_billing_account_path(billing_account) assert expected == actual @@ -3463,9 +4201,12 @@ def test_parse_common_billing_account_path(): actual = LocalInventoryServiceClient.parse_common_billing_account_path(path) assert expected == actual + def test_common_folder_path(): folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) + expected = "folders/{folder}".format( + folder=folder, + ) actual = LocalInventoryServiceClient.common_folder_path(folder) assert expected == actual @@ -3480,9 +4221,12 @@ def test_parse_common_folder_path(): actual = LocalInventoryServiceClient.parse_common_folder_path(path) assert expected == actual + def test_common_organization_path(): organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) + expected = "organizations/{organization}".format( + organization=organization, + ) actual = LocalInventoryServiceClient.common_organization_path(organization) assert expected == actual @@ -3497,9 +4241,12 @@ def test_parse_common_organization_path(): actual = LocalInventoryServiceClient.parse_common_organization_path(path) assert expected == actual + def test_common_project_path(): project = "squid" - expected = "projects/{project}".format(project=project, ) + expected = "projects/{project}".format( + project=project, + ) actual = LocalInventoryServiceClient.common_project_path(project) assert expected == actual @@ -3514,10 +4261,14 @@ def test_parse_common_project_path(): actual = LocalInventoryServiceClient.parse_common_project_path(path) assert expected == actual + def test_common_location_path(): project = "whelk" location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) actual = LocalInventoryServiceClient.common_location_path(project, location) assert expected == actual @@ -3537,14 +4288,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.LocalInventoryServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.LocalInventoryServiceTransport, "_prep_wrapped_messages" + ) as prep: client = LocalInventoryServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.LocalInventoryServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.LocalInventoryServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = LocalInventoryServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -3555,10 +4310,11 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = LocalInventoryServiceClient( - 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() @@ -3567,10 +4323,11 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = LocalInventoryServiceAsyncClient( - 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() @@ -3578,10 +4335,11 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = LocalInventoryServiceClient( - 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() @@ -3589,13 +4347,12 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = LocalInventoryServiceClient( - 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: @@ -3604,10 +4361,17 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport), - (LocalInventoryServiceAsyncClient, transports.LocalInventoryServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (LocalInventoryServiceClient, transports.LocalInventoryServiceGrpcTransport), + ( + LocalInventoryServiceAsyncClient, + transports.LocalInventoryServiceGrpcAsyncIOTransport, + ), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -3622,7 +4386,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/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/merchant_inventories_v1/test_regional_inventory_service.py b/packages/google-shopping-merchant-inventories/tests/unit/gapic/merchant_inventories_v1/test_regional_inventory_service.py similarity index 68% rename from owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/merchant_inventories_v1/test_regional_inventory_service.py rename to packages/google-shopping-merchant-inventories/tests/unit/gapic/merchant_inventories_v1/test_regional_inventory_service.py index 1043a9504607..37cb792875d0 100644 --- a/owl-bot-staging/google-shopping-merchant-inventories/v1/tests/unit/gapic/merchant_inventories_v1/test_regional_inventory_service.py +++ b/packages/google-shopping-merchant-inventories/tests/unit/gapic/merchant_inventories_v1/test_regional_inventory_service.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,49 +22,49 @@ 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 +from collections.abc import AsyncIterable, Iterable import json import math -import pytest + from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule +from google.protobuf import json_format +import grpc +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 +import pytest +from requests import PreparedRequest, Request, Response 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.oauth2 import service_account from google.protobuf import timestamp_pb2 # type: ignore -from google.shopping.merchant_inventories_v1.services.regional_inventory_service import RegionalInventoryServiceAsyncClient -from google.shopping.merchant_inventories_v1.services.regional_inventory_service import RegionalInventoryServiceClient -from google.shopping.merchant_inventories_v1.services.regional_inventory_service import pagers -from google.shopping.merchant_inventories_v1.services.regional_inventory_service import transports -from google.shopping.merchant_inventories_v1.types import inventories_common -from google.shopping.merchant_inventories_v1.types import regionalinventory from google.shopping.type.types import types from google.type import interval_pb2 # type: ignore -import google.auth - +from google.shopping.merchant_inventories_v1.services.regional_inventory_service import ( + RegionalInventoryServiceAsyncClient, + RegionalInventoryServiceClient, + pagers, + transports, +) +from google.shopping.merchant_inventories_v1.types import ( + inventories_common, + regionalinventory, +) CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -78,9 +79,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(): @@ -88,17 +91,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(): @@ -109,101 +122,245 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert RegionalInventoryServiceClient._get_default_mtls_endpoint(None) is None - assert RegionalInventoryServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert RegionalInventoryServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert RegionalInventoryServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert RegionalInventoryServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert RegionalInventoryServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ( + RegionalInventoryServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + RegionalInventoryServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + RegionalInventoryServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + RegionalInventoryServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + RegionalInventoryServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + def test__read_environment_variables(): - assert RegionalInventoryServiceClient._read_environment_variables() == (False, "auto", None) + assert RegionalInventoryServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert RegionalInventoryServiceClient._read_environment_variables() == (True, "auto", None) + assert RegionalInventoryServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert RegionalInventoryServiceClient._read_environment_variables() == (False, "auto", None) + assert RegionalInventoryServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) - 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) as excinfo: RegionalInventoryServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert RegionalInventoryServiceClient._read_environment_variables() == (False, "never", None) + assert RegionalInventoryServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert RegionalInventoryServiceClient._read_environment_variables() == (False, "always", None) + assert RegionalInventoryServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert RegionalInventoryServiceClient._read_environment_variables() == (False, "auto", None) + assert RegionalInventoryServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: RegionalInventoryServiceClient._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 RegionalInventoryServiceClient._read_environment_variables() == (False, "auto", "foo.com") + assert RegionalInventoryServiceClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + def test__get_client_cert_source(): mock_provided_cert_source = mock.Mock() mock_default_cert_source = mock.Mock() assert RegionalInventoryServiceClient._get_client_cert_source(None, False) is None - assert RegionalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert RegionalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + assert ( + RegionalInventoryServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + RegionalInventoryServiceClient._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 ( + RegionalInventoryServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + RegionalInventoryServiceClient._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 RegionalInventoryServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert RegionalInventoryServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source -@mock.patch.object(RegionalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceClient)) -@mock.patch.object(RegionalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceAsyncClient)) +@mock.patch.object( + RegionalInventoryServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionalInventoryServiceClient), +) +@mock.patch.object( + RegionalInventoryServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionalInventoryServiceAsyncClient), +) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = RegionalInventoryServiceClient._DEFAULT_UNIVERSE - default_endpoint = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) - assert RegionalInventoryServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert RegionalInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - assert RegionalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert RegionalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "always") == RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - assert RegionalInventoryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT - assert RegionalInventoryServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert RegionalInventoryServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + assert ( + RegionalInventoryServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + RegionalInventoryServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + RegionalInventoryServiceClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + RegionalInventoryServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + RegionalInventoryServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == RegionalInventoryServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + RegionalInventoryServiceClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + RegionalInventoryServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) with pytest.raises(MutualTLSChannelError) as excinfo: - RegionalInventoryServiceClient._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." + RegionalInventoryServiceClient._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 RegionalInventoryServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert RegionalInventoryServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert RegionalInventoryServiceClient._get_universe_domain(None, None) == RegionalInventoryServiceClient._DEFAULT_UNIVERSE + assert ( + RegionalInventoryServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + RegionalInventoryServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + RegionalInventoryServiceClient._get_universe_domain(None, None) + == RegionalInventoryServiceClient._DEFAULT_UNIVERSE + ) with pytest.raises(ValueError) as excinfo: RegionalInventoryServiceClient._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) @@ -219,7 +376,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") @@ -232,14 +390,22 @@ 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", [ - (RegionalInventoryServiceClient, "grpc"), - (RegionalInventoryServiceAsyncClient, "grpc_asyncio"), - (RegionalInventoryServiceClient, "rest"), -]) -def test_regional_inventory_service_client_from_service_account_info(client_class, transport_name): + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (RegionalInventoryServiceClient, "grpc"), + (RegionalInventoryServiceAsyncClient, "grpc_asyncio"), + (RegionalInventoryServiceClient, "rest"), + ], +) +def test_regional_inventory_service_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) @@ -247,52 +413,70 @@ def test_regional_inventory_service_client_from_service_account_info(client_clas assert isinstance(client, client_class) assert client.transport._host == ( - 'merchantapi.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://merchantapi.googleapis.com' + "merchantapi.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://merchantapi.googleapis.com" ) -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.RegionalInventoryServiceGrpcTransport, "grpc"), - (transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.RegionalInventoryServiceRestTransport, "rest"), -]) -def test_regional_inventory_service_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.RegionalInventoryServiceGrpcTransport, "grpc"), + (transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.RegionalInventoryServiceRestTransport, "rest"), + ], +) +def test_regional_inventory_service_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", [ - (RegionalInventoryServiceClient, "grpc"), - (RegionalInventoryServiceAsyncClient, "grpc_asyncio"), - (RegionalInventoryServiceClient, "rest"), -]) -def test_regional_inventory_service_client_from_service_account_file(client_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (RegionalInventoryServiceClient, "grpc"), + (RegionalInventoryServiceAsyncClient, "grpc_asyncio"), + (RegionalInventoryServiceClient, "rest"), + ], +) +def test_regional_inventory_service_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 == ( - 'merchantapi.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://merchantapi.googleapis.com' + "merchantapi.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://merchantapi.googleapis.com" ) @@ -308,30 +492,57 @@ def test_regional_inventory_service_client_get_transport_class(): assert transport == transports.RegionalInventoryServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc"), - (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest"), -]) -@mock.patch.object(RegionalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceClient)) -@mock.patch.object(RegionalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceAsyncClient)) -def test_regional_inventory_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + RegionalInventoryServiceClient, + transports.RegionalInventoryServiceGrpcTransport, + "grpc", + ), + ( + RegionalInventoryServiceAsyncClient, + transports.RegionalInventoryServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + RegionalInventoryServiceClient, + transports.RegionalInventoryServiceRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + RegionalInventoryServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionalInventoryServiceClient), +) +@mock.patch.object( + RegionalInventoryServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionalInventoryServiceAsyncClient), +) +def test_regional_inventory_service_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(RegionalInventoryServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object( + RegionalInventoryServiceClient, "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(RegionalInventoryServiceClient, 'get_transport_class') as gtc: + with mock.patch.object( + RegionalInventoryServiceClient, "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( @@ -349,13 +560,15 @@ def test_regional_inventory_service_client_client_options(client_class, transpor # 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, @@ -367,7 +580,7 @@ def test_regional_inventory_service_client_client_options(client_class, transpor # 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( @@ -387,23 +600,33 @@ def test_regional_inventory_service_client_client_options(client_class, transpor 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 GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - 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) as excinfo: client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) # 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", @@ -412,48 +635,102 @@ def test_regional_inventory_service_client_client_options(client_class, transpor 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", [ - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc", "true"), - (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc", "false"), - (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest", "true"), - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(RegionalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceClient)) -@mock.patch.object(RegionalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + RegionalInventoryServiceClient, + transports.RegionalInventoryServiceGrpcTransport, + "grpc", + "true", + ), + ( + RegionalInventoryServiceAsyncClient, + transports.RegionalInventoryServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + RegionalInventoryServiceClient, + transports.RegionalInventoryServiceGrpcTransport, + "grpc", + "false", + ), + ( + RegionalInventoryServiceAsyncClient, + transports.RegionalInventoryServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + RegionalInventoryServiceClient, + transports.RegionalInventoryServiceRestTransport, + "rest", + "true", + ), + ( + RegionalInventoryServiceClient, + transports.RegionalInventoryServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + RegionalInventoryServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionalInventoryServiceClient), +) +@mock.patch.object( + RegionalInventoryServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionalInventoryServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_regional_inventory_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_regional_inventory_service_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 @@ -472,12 +749,22 @@ def test_regional_inventory_service_client_mtls_env_auto(client_class, transport # 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 @@ -498,15 +785,22 @@ def test_regional_inventory_service_client_mtls_env_auto(client_class, transport ) # 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, @@ -516,19 +810,34 @@ def test_regional_inventory_service_client_mtls_env_auto(client_class, transport ) -@pytest.mark.parametrize("client_class", [ - RegionalInventoryServiceClient, RegionalInventoryServiceAsyncClient -]) -@mock.patch.object(RegionalInventoryServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegionalInventoryServiceClient)) -@mock.patch.object(RegionalInventoryServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegionalInventoryServiceAsyncClient)) -def test_regional_inventory_service_client_get_mtls_endpoint_and_cert_source(client_class): +@pytest.mark.parametrize( + "client_class", + [RegionalInventoryServiceClient, RegionalInventoryServiceAsyncClient], +) +@mock.patch.object( + RegionalInventoryServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RegionalInventoryServiceClient), +) +@mock.patch.object( + RegionalInventoryServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RegionalInventoryServiceAsyncClient), +) +def test_regional_inventory_service_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 @@ -536,8 +845,12 @@ def test_regional_inventory_service_client_get_mtls_endpoint_and_cert_source(cli 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 @@ -555,16 +868,28 @@ def test_regional_inventory_service_client_get_mtls_endpoint_and_cert_source(cli # 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 @@ -574,34 +899,63 @@ def test_regional_inventory_service_client_get_mtls_endpoint_and_cert_source(cli 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`" + ) # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - 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) as excinfo: client_class.get_mtls_endpoint_and_cert_source() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + -@pytest.mark.parametrize("client_class", [ - RegionalInventoryServiceClient, RegionalInventoryServiceAsyncClient -]) -@mock.patch.object(RegionalInventoryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceClient)) -@mock.patch.object(RegionalInventoryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionalInventoryServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", + [RegionalInventoryServiceClient, RegionalInventoryServiceAsyncClient], +) +@mock.patch.object( + RegionalInventoryServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionalInventoryServiceClient), +) +@mock.patch.object( + RegionalInventoryServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionalInventoryServiceAsyncClient), +) def test_regional_inventory_service_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = RegionalInventoryServiceClient._DEFAULT_UNIVERSE - default_endpoint = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = RegionalInventoryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = RegionalInventoryServiceClient._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", @@ -624,11 +978,19 @@ def test_regional_inventory_service_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. @@ -636,27 +998,48 @@ def test_regional_inventory_service_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", [ - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc"), - (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest"), -]) -def test_regional_inventory_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + RegionalInventoryServiceClient, + transports.RegionalInventoryServiceGrpcTransport, + "grpc", + ), + ( + RegionalInventoryServiceAsyncClient, + transports.RegionalInventoryServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + RegionalInventoryServiceClient, + transports.RegionalInventoryServiceRestTransport, + "rest", + ), + ], +) +def test_regional_inventory_service_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, @@ -665,24 +1048,45 @@ def test_regional_inventory_service_client_client_options_scopes(client_class, t api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc", grpc_helpers), - (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceRestTransport, "rest", None), -]) -def test_regional_inventory_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + RegionalInventoryServiceClient, + transports.RegionalInventoryServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + RegionalInventoryServiceAsyncClient, + transports.RegionalInventoryServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + RegionalInventoryServiceClient, + transports.RegionalInventoryServiceRestTransport, + "rest", + None, + ), + ], +) +def test_regional_inventory_service_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, @@ -691,11 +1095,14 @@ def test_regional_inventory_service_client_client_options_credentials_file(clien api_audience=None, ) + def test_regional_inventory_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_inventories_v1.services.regional_inventory_service.transports.RegionalInventoryServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.shopping.merchant_inventories_v1.services.regional_inventory_service.transports.RegionalInventoryServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = RegionalInventoryServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -710,23 +1117,38 @@ def test_regional_inventory_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport, "grpc", grpc_helpers), - (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_regional_inventory_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + RegionalInventoryServiceClient, + transports.RegionalInventoryServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + RegionalInventoryServiceAsyncClient, + transports.RegionalInventoryServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_regional_inventory_service_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, @@ -753,9 +1175,7 @@ def test_regional_inventory_service_client_create_channel_credentials_file(clien credentials=file_creds, credentials_file=None, quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/content', -), + default_scopes=("https://www.googleapis.com/auth/content",), scopes=None, default_host="merchantapi.googleapis.com", ssl_credentials=None, @@ -766,11 +1186,14 @@ def test_regional_inventory_service_client_create_channel_credentials_file(clien ) -@pytest.mark.parametrize("request_type", [ - regionalinventory.ListRegionalInventoriesRequest, - dict, -]) -def test_list_regional_inventories(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + regionalinventory.ListRegionalInventoriesRequest, + dict, + ], +) +def test_list_regional_inventories(request_type, transport: str = "grpc"): client = RegionalInventoryServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -782,11 +1205,11 @@ def test_list_regional_inventories(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_regional_inventories), - '__call__') as call: + type(client.transport.list_regional_inventories), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = regionalinventory.ListRegionalInventoriesResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) response = client.list_regional_inventories(request) @@ -798,7 +1221,7 @@ def test_list_regional_inventories(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListRegionalInventoriesPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" def test_list_regional_inventories_non_empty_request_with_auto_populated_field(): @@ -806,30 +1229,33 @@ def test_list_regional_inventories_non_empty_request_with_auto_populated_field() # automatically populated, according to AIP-4235, with non-empty requests. client = RegionalInventoryServiceClient( 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 = regionalinventory.ListRegionalInventoriesRequest( - 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_regional_inventories), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.list_regional_inventories), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.list_regional_inventories(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == regionalinventory.ListRegionalInventoriesRequest( - parent='parent_value', - page_token='page_token_value', + parent="parent_value", + page_token="page_token_value", ) + def test_list_regional_inventories_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -844,12 +1270,19 @@ def test_list_regional_inventories_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_regional_inventories in client._transport._wrapped_methods + assert ( + client._transport.list_regional_inventories + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_regional_inventories] = 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_regional_inventories + ] = mock_rpc request = {} client.list_regional_inventories(request) @@ -862,8 +1295,11 @@ def test_list_regional_inventories_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_regional_inventories_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_list_regional_inventories_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: @@ -877,12 +1313,17 @@ async def test_list_regional_inventories_async_use_cached_wrapped_rpc(transport: wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.list_regional_inventories in client._client._transport._wrapped_methods + assert ( + client._client._transport.list_regional_inventories + 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_regional_inventories] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.list_regional_inventories + ] = mock_rpc request = {} await client.list_regional_inventories(request) @@ -896,8 +1337,12 @@ async def test_list_regional_inventories_async_use_cached_wrapped_rpc(transport: assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_regional_inventories_async(transport: str = 'grpc_asyncio', request_type=regionalinventory.ListRegionalInventoriesRequest): +async def test_list_regional_inventories_async( + transport: str = "grpc_asyncio", + request_type=regionalinventory.ListRegionalInventoriesRequest, +): client = RegionalInventoryServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -909,12 +1354,14 @@ async def test_list_regional_inventories_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_regional_inventories), - '__call__') as call: + type(client.transport.list_regional_inventories), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.ListRegionalInventoriesResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + regionalinventory.ListRegionalInventoriesResponse( + next_page_token="next_page_token_value", + ) + ) response = await client.list_regional_inventories(request) # Establish that the underlying gRPC stub method was called. @@ -925,13 +1372,14 @@ async def test_list_regional_inventories_async(transport: str = 'grpc_asyncio', # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListRegionalInventoriesAsyncPager) - 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_regional_inventories_async_from_dict(): await test_list_regional_inventories_async(request_type=dict) + def test_list_regional_inventories_field_headers(): client = RegionalInventoryServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -941,12 +1389,12 @@ def test_list_regional_inventories_field_headers(): # a field header. Set these to a non-empty value. request = regionalinventory.ListRegionalInventoriesRequest() - 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_regional_inventories), - '__call__') as call: + type(client.transport.list_regional_inventories), "__call__" + ) as call: call.return_value = regionalinventory.ListRegionalInventoriesResponse() client.list_regional_inventories(request) @@ -958,9 +1406,9 @@ def test_list_regional_inventories_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 @@ -973,13 +1421,15 @@ async def test_list_regional_inventories_field_headers_async(): # a field header. Set these to a non-empty value. request = regionalinventory.ListRegionalInventoriesRequest() - 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_regional_inventories), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.ListRegionalInventoriesResponse()) + type(client.transport.list_regional_inventories), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + regionalinventory.ListRegionalInventoriesResponse() + ) await client.list_regional_inventories(request) # Establish that the underlying gRPC stub method was called. @@ -990,9 +1440,9 @@ async def test_list_regional_inventories_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_regional_inventories_flattened(): @@ -1002,14 +1452,14 @@ def test_list_regional_inventories_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__') as call: + type(client.transport.list_regional_inventories), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = regionalinventory.ListRegionalInventoriesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_regional_inventories( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1017,7 +1467,7 @@ def test_list_regional_inventories_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 @@ -1031,9 +1481,10 @@ def test_list_regional_inventories_flattened_error(): with pytest.raises(ValueError): client.list_regional_inventories( regionalinventory.ListRegionalInventoriesRequest(), - parent='parent_value', + parent="parent_value", ) + @pytest.mark.asyncio async def test_list_regional_inventories_flattened_async(): client = RegionalInventoryServiceAsyncClient( @@ -1042,16 +1493,18 @@ async def test_list_regional_inventories_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__') as call: + type(client.transport.list_regional_inventories), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = regionalinventory.ListRegionalInventoriesResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.ListRegionalInventoriesResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + regionalinventory.ListRegionalInventoriesResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_regional_inventories( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1059,9 +1512,10 @@ async def test_list_regional_inventories_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_regional_inventories_flattened_error_async(): client = RegionalInventoryServiceAsyncClient( @@ -1073,7 +1527,7 @@ async def test_list_regional_inventories_flattened_error_async(): with pytest.raises(ValueError): await client.list_regional_inventories( regionalinventory.ListRegionalInventoriesRequest(), - parent='parent_value', + parent="parent_value", ) @@ -1085,8 +1539,8 @@ def test_list_regional_inventories_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_regional_inventories), - '__call__') as call: + type(client.transport.list_regional_inventories), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( regionalinventory.ListRegionalInventoriesResponse( @@ -1095,17 +1549,17 @@ def test_list_regional_inventories_pager(transport_name: str = "grpc"): regionalinventory.RegionalInventory(), regionalinventory.RegionalInventory(), ], - next_page_token='abc', + next_page_token="abc", ), regionalinventory.ListRegionalInventoriesResponse( regional_inventories=[], - next_page_token='def', + next_page_token="def", ), regionalinventory.ListRegionalInventoriesResponse( regional_inventories=[ regionalinventory.RegionalInventory(), ], - next_page_token='ghi', + next_page_token="ghi", ), regionalinventory.ListRegionalInventoriesResponse( regional_inventories=[ @@ -1120,11 +1574,11 @@ def test_list_regional_inventories_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_regional_inventories( + request={}, retry=retry, timeout=timeout ) - pager = client.list_regional_inventories(request={}, retry=retry, timeout=timeout) assert pager._metadata == expected_metadata assert pager._retry == retry @@ -1132,8 +1586,9 @@ def test_list_regional_inventories_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, regionalinventory.RegionalInventory) - for i in results) + assert all(isinstance(i, regionalinventory.RegionalInventory) for i in results) + + def test_list_regional_inventories_pages(transport_name: str = "grpc"): client = RegionalInventoryServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1142,8 +1597,8 @@ def test_list_regional_inventories_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_regional_inventories), - '__call__') as call: + type(client.transport.list_regional_inventories), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( regionalinventory.ListRegionalInventoriesResponse( @@ -1152,17 +1607,17 @@ def test_list_regional_inventories_pages(transport_name: str = "grpc"): regionalinventory.RegionalInventory(), regionalinventory.RegionalInventory(), ], - next_page_token='abc', + next_page_token="abc", ), regionalinventory.ListRegionalInventoriesResponse( regional_inventories=[], - next_page_token='def', + next_page_token="def", ), regionalinventory.ListRegionalInventoriesResponse( regional_inventories=[ regionalinventory.RegionalInventory(), ], - next_page_token='ghi', + next_page_token="ghi", ), regionalinventory.ListRegionalInventoriesResponse( regional_inventories=[ @@ -1173,9 +1628,10 @@ def test_list_regional_inventories_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_regional_inventories(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_regional_inventories_async_pager(): client = RegionalInventoryServiceAsyncClient( @@ -1184,8 +1640,10 @@ async def test_list_regional_inventories_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_regional_inventories), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( regionalinventory.ListRegionalInventoriesResponse( @@ -1194,17 +1652,17 @@ async def test_list_regional_inventories_async_pager(): regionalinventory.RegionalInventory(), regionalinventory.RegionalInventory(), ], - next_page_token='abc', + next_page_token="abc", ), regionalinventory.ListRegionalInventoriesResponse( regional_inventories=[], - next_page_token='def', + next_page_token="def", ), regionalinventory.ListRegionalInventoriesResponse( regional_inventories=[ regionalinventory.RegionalInventory(), ], - next_page_token='ghi', + next_page_token="ghi", ), regionalinventory.ListRegionalInventoriesResponse( regional_inventories=[ @@ -1214,15 +1672,18 @@ async def test_list_regional_inventories_async_pager(): ), RuntimeError, ) - async_pager = await client.list_regional_inventories(request={},) - assert async_pager.next_page_token == 'abc' + async_pager = await client.list_regional_inventories( + 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, regionalinventory.RegionalInventory) - for i in responses) + assert all( + isinstance(i, regionalinventory.RegionalInventory) for i in responses + ) @pytest.mark.asyncio @@ -1233,8 +1694,10 @@ async def test_list_regional_inventories_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_regional_inventories), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( regionalinventory.ListRegionalInventoriesResponse( @@ -1243,17 +1706,17 @@ async def test_list_regional_inventories_async_pages(): regionalinventory.RegionalInventory(), regionalinventory.RegionalInventory(), ], - next_page_token='abc', + next_page_token="abc", ), regionalinventory.ListRegionalInventoriesResponse( regional_inventories=[], - next_page_token='def', + next_page_token="def", ), regionalinventory.ListRegionalInventoriesResponse( regional_inventories=[ regionalinventory.RegionalInventory(), ], - next_page_token='ghi', + next_page_token="ghi", ), regionalinventory.ListRegionalInventoriesResponse( regional_inventories=[ @@ -1266,18 +1729,22 @@ async def test_list_regional_inventories_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_regional_inventories(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", [ - regionalinventory.InsertRegionalInventoryRequest, - dict, -]) -def test_insert_regional_inventory(request_type, transport: str = 'grpc'): + +@pytest.mark.parametrize( + "request_type", + [ + regionalinventory.InsertRegionalInventoryRequest, + dict, + ], +) +def test_insert_regional_inventory(request_type, transport: str = "grpc"): client = RegionalInventoryServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1289,13 +1756,13 @@ def test_insert_regional_inventory(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.insert_regional_inventory), - '__call__') as call: + type(client.transport.insert_regional_inventory), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = regionalinventory.RegionalInventory( - name='name_value', + name="name_value", account=749, - region='region_value', + region="region_value", ) response = client.insert_regional_inventory(request) @@ -1307,9 +1774,9 @@ def test_insert_regional_inventory(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, regionalinventory.RegionalInventory) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.account == 749 - assert response.region == 'region_value' + assert response.region == "region_value" def test_insert_regional_inventory_non_empty_request_with_auto_populated_field(): @@ -1317,28 +1784,31 @@ def test_insert_regional_inventory_non_empty_request_with_auto_populated_field() # automatically populated, according to AIP-4235, with non-empty requests. client = RegionalInventoryServiceClient( 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 = regionalinventory.InsertRegionalInventoryRequest( - 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.insert_regional_inventory), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.insert_regional_inventory), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.insert_regional_inventory(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == regionalinventory.InsertRegionalInventoryRequest( - parent='parent_value', + parent="parent_value", ) + def test_insert_regional_inventory_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1353,12 +1823,19 @@ def test_insert_regional_inventory_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.insert_regional_inventory in client._transport._wrapped_methods + assert ( + client._transport.insert_regional_inventory + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.insert_regional_inventory] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.insert_regional_inventory + ] = mock_rpc request = {} client.insert_regional_inventory(request) @@ -1371,8 +1848,11 @@ def test_insert_regional_inventory_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_insert_regional_inventory_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_insert_regional_inventory_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: @@ -1386,12 +1866,17 @@ async def test_insert_regional_inventory_async_use_cached_wrapped_rpc(transport: wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.insert_regional_inventory in client._client._transport._wrapped_methods + assert ( + client._client._transport.insert_regional_inventory + 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.insert_regional_inventory] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.insert_regional_inventory + ] = mock_rpc request = {} await client.insert_regional_inventory(request) @@ -1405,8 +1890,12 @@ async def test_insert_regional_inventory_async_use_cached_wrapped_rpc(transport: assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_insert_regional_inventory_async(transport: str = 'grpc_asyncio', request_type=regionalinventory.InsertRegionalInventoryRequest): +async def test_insert_regional_inventory_async( + transport: str = "grpc_asyncio", + request_type=regionalinventory.InsertRegionalInventoryRequest, +): client = RegionalInventoryServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1418,14 +1907,16 @@ async def test_insert_regional_inventory_async(transport: str = 'grpc_asyncio', # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.insert_regional_inventory), - '__call__') as call: + type(client.transport.insert_regional_inventory), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.RegionalInventory( - name='name_value', - account=749, - region='region_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + regionalinventory.RegionalInventory( + name="name_value", + account=749, + region="region_value", + ) + ) response = await client.insert_regional_inventory(request) # Establish that the underlying gRPC stub method was called. @@ -1436,15 +1927,16 @@ async def test_insert_regional_inventory_async(transport: str = 'grpc_asyncio', # Establish that the response is the type that we expect. assert isinstance(response, regionalinventory.RegionalInventory) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.account == 749 - assert response.region == 'region_value' + assert response.region == "region_value" @pytest.mark.asyncio async def test_insert_regional_inventory_async_from_dict(): await test_insert_regional_inventory_async(request_type=dict) + def test_insert_regional_inventory_field_headers(): client = RegionalInventoryServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1454,12 +1946,12 @@ def test_insert_regional_inventory_field_headers(): # a field header. Set these to a non-empty value. request = regionalinventory.InsertRegionalInventoryRequest() - 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.insert_regional_inventory), - '__call__') as call: + type(client.transport.insert_regional_inventory), "__call__" + ) as call: call.return_value = regionalinventory.RegionalInventory() client.insert_regional_inventory(request) @@ -1471,9 +1963,9 @@ def test_insert_regional_inventory_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 @@ -1486,13 +1978,15 @@ async def test_insert_regional_inventory_field_headers_async(): # a field header. Set these to a non-empty value. request = regionalinventory.InsertRegionalInventoryRequest() - 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.insert_regional_inventory), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.RegionalInventory()) + type(client.transport.insert_regional_inventory), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + regionalinventory.RegionalInventory() + ) await client.insert_regional_inventory(request) # Establish that the underlying gRPC stub method was called. @@ -1503,16 +1997,19 @@ async def test_insert_regional_inventory_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"] -@pytest.mark.parametrize("request_type", [ - regionalinventory.DeleteRegionalInventoryRequest, - dict, -]) -def test_delete_regional_inventory(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + regionalinventory.DeleteRegionalInventoryRequest, + dict, + ], +) +def test_delete_regional_inventory(request_type, transport: str = "grpc"): client = RegionalInventoryServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1524,8 +2021,8 @@ def test_delete_regional_inventory(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_regional_inventory), - '__call__') as call: + type(client.transport.delete_regional_inventory), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = None response = client.delete_regional_inventory(request) @@ -1545,28 +2042,31 @@ def test_delete_regional_inventory_non_empty_request_with_auto_populated_field() # automatically populated, according to AIP-4235, with non-empty requests. client = RegionalInventoryServiceClient( 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 = regionalinventory.DeleteRegionalInventoryRequest( - 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_regional_inventory), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.delete_regional_inventory), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.delete_regional_inventory(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == regionalinventory.DeleteRegionalInventoryRequest( - name='name_value', + name="name_value", ) + def test_delete_regional_inventory_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1581,12 +2081,19 @@ def test_delete_regional_inventory_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_regional_inventory in client._transport._wrapped_methods + assert ( + client._transport.delete_regional_inventory + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_regional_inventory] = 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_regional_inventory + ] = mock_rpc request = {} client.delete_regional_inventory(request) @@ -1599,8 +2106,11 @@ def test_delete_regional_inventory_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_delete_regional_inventory_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_delete_regional_inventory_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: @@ -1614,12 +2124,17 @@ async def test_delete_regional_inventory_async_use_cached_wrapped_rpc(transport: wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.delete_regional_inventory in client._client._transport._wrapped_methods + assert ( + client._client._transport.delete_regional_inventory + 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_regional_inventory] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.delete_regional_inventory + ] = mock_rpc request = {} await client.delete_regional_inventory(request) @@ -1633,8 +2148,12 @@ async def test_delete_regional_inventory_async_use_cached_wrapped_rpc(transport: assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_delete_regional_inventory_async(transport: str = 'grpc_asyncio', request_type=regionalinventory.DeleteRegionalInventoryRequest): +async def test_delete_regional_inventory_async( + transport: str = "grpc_asyncio", + request_type=regionalinventory.DeleteRegionalInventoryRequest, +): client = RegionalInventoryServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1646,8 +2165,8 @@ async def test_delete_regional_inventory_async(transport: str = 'grpc_asyncio', # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_regional_inventory), - '__call__') as call: + type(client.transport.delete_regional_inventory), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.delete_regional_inventory(request) @@ -1666,6 +2185,7 @@ async def test_delete_regional_inventory_async(transport: str = 'grpc_asyncio', async def test_delete_regional_inventory_async_from_dict(): await test_delete_regional_inventory_async(request_type=dict) + def test_delete_regional_inventory_field_headers(): client = RegionalInventoryServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1675,12 +2195,12 @@ def test_delete_regional_inventory_field_headers(): # a field header. Set these to a non-empty value. request = regionalinventory.DeleteRegionalInventoryRequest() - 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_regional_inventory), - '__call__') as call: + type(client.transport.delete_regional_inventory), "__call__" + ) as call: call.return_value = None client.delete_regional_inventory(request) @@ -1692,9 +2212,9 @@ def test_delete_regional_inventory_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 @@ -1707,12 +2227,12 @@ async def test_delete_regional_inventory_field_headers_async(): # a field header. Set these to a non-empty value. request = regionalinventory.DeleteRegionalInventoryRequest() - 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_regional_inventory), - '__call__') as call: + type(client.transport.delete_regional_inventory), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_regional_inventory(request) @@ -1724,9 +2244,9 @@ async def test_delete_regional_inventory_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_regional_inventory_flattened(): @@ -1736,14 +2256,14 @@ def test_delete_regional_inventory_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_regional_inventory), - '__call__') as call: + type(client.transport.delete_regional_inventory), "__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_regional_inventory( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1751,7 +2271,7 @@ def test_delete_regional_inventory_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 @@ -1765,9 +2285,10 @@ def test_delete_regional_inventory_flattened_error(): with pytest.raises(ValueError): client.delete_regional_inventory( regionalinventory.DeleteRegionalInventoryRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_delete_regional_inventory_flattened_async(): client = RegionalInventoryServiceAsyncClient( @@ -1776,8 +2297,8 @@ async def test_delete_regional_inventory_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_regional_inventory), - '__call__') as call: + type(client.transport.delete_regional_inventory), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = None @@ -1785,7 +2306,7 @@ async def test_delete_regional_inventory_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.delete_regional_inventory( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1793,9 +2314,10 @@ async def test_delete_regional_inventory_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_regional_inventory_flattened_error_async(): client = RegionalInventoryServiceAsyncClient( @@ -1807,7 +2329,7 @@ async def test_delete_regional_inventory_flattened_error_async(): with pytest.raises(ValueError): await client.delete_regional_inventory( regionalinventory.DeleteRegionalInventoryRequest(), - name='name_value', + name="name_value", ) @@ -1825,12 +2347,19 @@ def test_list_regional_inventories_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_regional_inventories in client._transport._wrapped_methods + assert ( + client._transport.list_regional_inventories + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_regional_inventories] = 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_regional_inventories + ] = mock_rpc request = {} client.list_regional_inventories(request) @@ -1845,57 +2374,67 @@ def test_list_regional_inventories_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_list_regional_inventories_rest_required_fields(request_type=regionalinventory.ListRegionalInventoriesRequest): +def test_list_regional_inventories_rest_required_fields( + request_type=regionalinventory.ListRegionalInventoriesRequest, +): transport_class = transports.RegionalInventoryServiceRestTransport 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_regional_inventories._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_regional_inventories._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_regional_inventories._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_regional_inventories._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 = RegionalInventoryServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = regionalinventory.ListRegionalInventoriesResponse() # 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 @@ -1903,27 +2442,37 @@ def test_list_regional_inventories_rest_required_fields(request_type=regionalinv response_value.status_code = 200 # Convert return value to protobuf type - return_value = regionalinventory.ListRegionalInventoriesResponse.pb(return_value) + return_value = regionalinventory.ListRegionalInventoriesResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_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_regional_inventories(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_regional_inventories_rest_unset_required_fields(): - transport = transports.RegionalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.RegionalInventoryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.list_regional_inventories._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_regional_inventories_rest_flattened(): @@ -1933,16 +2482,16 @@ def test_list_regional_inventories_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 = regionalinventory.ListRegionalInventoriesResponse() # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1/products/sample2'} + sample_request = {"parent": "accounts/sample1/products/sample2"} # get truthy value for each flattened field mock_args = dict( - parent='parent_value', + parent="parent_value", ) mock_args.update(sample_request) @@ -1950,9 +2499,11 @@ def test_list_regional_inventories_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = regionalinventory.ListRegionalInventoriesResponse.pb(return_value) + return_value = regionalinventory.ListRegionalInventoriesResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -1962,10 +2513,14 @@ def test_list_regional_inventories_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/inventories/v1/{parent=accounts/*/products/*}/regionalInventories" % client.transport._host, args[1]) + assert path_template.validate( + "%s/inventories/v1/{parent=accounts/*/products/*}/regionalInventories" + % client.transport._host, + args[1], + ) -def test_list_regional_inventories_rest_flattened_error(transport: str = 'rest'): +def test_list_regional_inventories_rest_flattened_error(transport: str = "rest"): client = RegionalInventoryServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1976,20 +2531,20 @@ def test_list_regional_inventories_rest_flattened_error(transport: str = 'rest') with pytest.raises(ValueError): client.list_regional_inventories( regionalinventory.ListRegionalInventoriesRequest(), - parent='parent_value', + parent="parent_value", ) -def test_list_regional_inventories_rest_pager(transport: str = 'rest'): +def test_list_regional_inventories_rest_pager(transport: str = "rest"): client = RegionalInventoryServiceClient( 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 = ( regionalinventory.ListRegionalInventoriesResponse( @@ -1998,17 +2553,17 @@ def test_list_regional_inventories_rest_pager(transport: str = 'rest'): regionalinventory.RegionalInventory(), regionalinventory.RegionalInventory(), ], - next_page_token='abc', + next_page_token="abc", ), regionalinventory.ListRegionalInventoriesResponse( regional_inventories=[], - next_page_token='def', + next_page_token="def", ), regionalinventory.ListRegionalInventoriesResponse( regional_inventories=[ regionalinventory.RegionalInventory(), ], - next_page_token='ghi', + next_page_token="ghi", ), regionalinventory.ListRegionalInventoriesResponse( regional_inventories=[ @@ -2021,24 +2576,26 @@ def test_list_regional_inventories_rest_pager(transport: str = 'rest'): response = response + response # Wrap the values into proper Response objs - response = tuple(regionalinventory.ListRegionalInventoriesResponse.to_json(x) for x in response) + response = tuple( + regionalinventory.ListRegionalInventoriesResponse.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': 'accounts/sample1/products/sample2'} + sample_request = {"parent": "accounts/sample1/products/sample2"} pager = client.list_regional_inventories(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, regionalinventory.RegionalInventory) - for i in results) + assert all(isinstance(i, regionalinventory.RegionalInventory) for i in results) pages = list(client.list_regional_inventories(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 @@ -2056,12 +2613,19 @@ def test_insert_regional_inventory_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.insert_regional_inventory in client._transport._wrapped_methods + assert ( + client._transport.insert_regional_inventory + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.insert_regional_inventory] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.insert_regional_inventory + ] = mock_rpc request = {} client.insert_regional_inventory(request) @@ -2076,57 +2640,62 @@ def test_insert_regional_inventory_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_insert_regional_inventory_rest_required_fields(request_type=regionalinventory.InsertRegionalInventoryRequest): +def test_insert_regional_inventory_rest_required_fields( + request_type=regionalinventory.InsertRegionalInventoryRequest, +): transport_class = transports.RegionalInventoryServiceRestTransport 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()).insert_regional_inventory._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).insert_regional_inventory._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()).insert_regional_inventory._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).insert_regional_inventory._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 = RegionalInventoryServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = regionalinventory.RegionalInventory() # 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() @@ -2136,24 +2705,32 @@ def test_insert_regional_inventory_rest_required_fields(request_type=regionalinv return_value = regionalinventory.RegionalInventory.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.insert_regional_inventory(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_insert_regional_inventory_rest_unset_required_fields(): - transport = transports.RegionalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.RegionalInventoryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.insert_regional_inventory._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "regionalInventory", ))) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "regionalInventory", + ) + ) + ) def test_delete_regional_inventory_rest_use_cached_wrapped_rpc(): @@ -2170,12 +2747,19 @@ def test_delete_regional_inventory_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_regional_inventory in client._transport._wrapped_methods + assert ( + client._transport.delete_regional_inventory + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_regional_inventory] = 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_regional_inventory + ] = mock_rpc request = {} client.delete_regional_inventory(request) @@ -2190,80 +2774,85 @@ def test_delete_regional_inventory_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_delete_regional_inventory_rest_required_fields(request_type=regionalinventory.DeleteRegionalInventoryRequest): +def test_delete_regional_inventory_rest_required_fields( + request_type=regionalinventory.DeleteRegionalInventoryRequest, +): transport_class = transports.RegionalInventoryServiceRestTransport 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_regional_inventory._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_regional_inventory._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_regional_inventory._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_regional_inventory._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 = RegionalInventoryServiceClient( 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_regional_inventory(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_regional_inventory_rest_unset_required_fields(): - transport = transports.RegionalInventoryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.RegionalInventoryServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.delete_regional_inventory._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_delete_regional_inventory_rest_flattened(): @@ -2273,24 +2862,26 @@ def test_delete_regional_inventory_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': 'accounts/sample1/products/sample2/regionalInventories/sample3'} + sample_request = { + "name": "accounts/sample1/products/sample2/regionalInventories/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"} @@ -2300,10 +2891,14 @@ def test_delete_regional_inventory_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/inventories/v1/{name=accounts/*/products/*/regionalInventories/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/inventories/v1/{name=accounts/*/products/*/regionalInventories/*}" + % client.transport._host, + args[1], + ) -def test_delete_regional_inventory_rest_flattened_error(transport: str = 'rest'): +def test_delete_regional_inventory_rest_flattened_error(transport: str = "rest"): client = RegionalInventoryServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2314,7 +2909,7 @@ def test_delete_regional_inventory_rest_flattened_error(transport: str = 'rest') with pytest.raises(ValueError): client.delete_regional_inventory( regionalinventory.DeleteRegionalInventoryRequest(), - name='name_value', + name="name_value", ) @@ -2356,8 +2951,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = RegionalInventoryServiceClient( - 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. @@ -2379,6 +2973,7 @@ def test_transport_instance(): client = RegionalInventoryServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.RegionalInventoryServiceGrpcTransport( @@ -2393,18 +2988,23 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.RegionalInventoryServiceGrpcTransport, - transports.RegionalInventoryServiceGrpcAsyncIOTransport, - transports.RegionalInventoryServiceRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RegionalInventoryServiceGrpcTransport, + transports.RegionalInventoryServiceGrpcAsyncIOTransport, + transports.RegionalInventoryServiceRestTransport, + ], +) 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 = RegionalInventoryServiceClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -2414,8 +3014,7 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) assert client is not None @@ -2430,8 +3029,8 @@ def test_list_regional_inventories_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__') as call: + type(client.transport.list_regional_inventories), "__call__" + ) as call: call.return_value = regionalinventory.ListRegionalInventoriesResponse() client.list_regional_inventories(request=None) @@ -2453,8 +3052,8 @@ def test_insert_regional_inventory_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.insert_regional_inventory), - '__call__') as call: + type(client.transport.insert_regional_inventory), "__call__" + ) as call: call.return_value = regionalinventory.RegionalInventory() client.insert_regional_inventory(request=None) @@ -2476,8 +3075,8 @@ def test_delete_regional_inventory_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_regional_inventory), - '__call__') as call: + type(client.transport.delete_regional_inventory), "__call__" + ) as call: call.return_value = None client.delete_regional_inventory(request=None) @@ -2498,8 +3097,7 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = RegionalInventoryServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) assert client is not None @@ -2515,12 +3113,14 @@ async def test_list_regional_inventories_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__') as call: + type(client.transport.list_regional_inventories), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.ListRegionalInventoriesResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + regionalinventory.ListRegionalInventoriesResponse( + next_page_token="next_page_token_value", + ) + ) await client.list_regional_inventories(request=None) # Establish that the underlying stub method was called. @@ -2542,14 +3142,16 @@ async def test_insert_regional_inventory_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.insert_regional_inventory), - '__call__') as call: + type(client.transport.insert_regional_inventory), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regionalinventory.RegionalInventory( - name='name_value', - account=749, - region='region_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + regionalinventory.RegionalInventory( + name="name_value", + account=749, + region="region_value", + ) + ) await client.insert_regional_inventory(request=None) # Establish that the underlying stub method was called. @@ -2571,8 +3173,8 @@ async def test_delete_regional_inventory_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_regional_inventory), - '__call__') as call: + type(client.transport.delete_regional_inventory), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_regional_inventory(request=None) @@ -2592,20 +3194,23 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_list_regional_inventories_rest_bad_request(request_type=regionalinventory.ListRegionalInventoriesRequest): +def test_list_regional_inventories_rest_bad_request( + request_type=regionalinventory.ListRegionalInventoriesRequest, +): client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/products/sample2'} + request_init = {"parent": "accounts/sample1/products/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() @@ -2614,25 +3219,27 @@ def test_list_regional_inventories_rest_bad_request(request_type=regionalinvento client.list_regional_inventories(request) -@pytest.mark.parametrize("request_type", [ - regionalinventory.ListRegionalInventoriesRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + regionalinventory.ListRegionalInventoriesRequest, + dict, + ], +) def test_list_regional_inventories_rest_call_success(request_type): client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/products/sample2'} + request_init = {"parent": "accounts/sample1/products/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 = regionalinventory.ListRegionalInventoriesResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -2640,35 +3247,50 @@ def test_list_regional_inventories_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = regionalinventory.ListRegionalInventoriesResponse.pb(return_value) + return_value = regionalinventory.ListRegionalInventoriesResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_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_regional_inventories(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListRegionalInventoriesPager) - 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_regional_inventories_rest_interceptors(null_interceptor): transport = transports.RegionalInventoryServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegionalInventoryServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.RegionalInventoryServiceRestInterceptor(), + ) client = RegionalInventoryServiceClient(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.RegionalInventoryServiceRestInterceptor, "post_list_regional_inventories") as post, \ - mock.patch.object(transports.RegionalInventoryServiceRestInterceptor, "post_list_regional_inventories_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.RegionalInventoryServiceRestInterceptor, "pre_list_regional_inventories") 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.RegionalInventoryServiceRestInterceptor, + "post_list_regional_inventories", + ) as post, mock.patch.object( + transports.RegionalInventoryServiceRestInterceptor, + "post_list_regional_inventories_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.RegionalInventoryServiceRestInterceptor, + "pre_list_regional_inventories", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = regionalinventory.ListRegionalInventoriesRequest.pb(regionalinventory.ListRegionalInventoriesRequest()) + pb_message = regionalinventory.ListRegionalInventoriesRequest.pb( + regionalinventory.ListRegionalInventoriesRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2679,39 +3301,53 @@ def test_list_regional_inventories_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 = regionalinventory.ListRegionalInventoriesResponse.to_json(regionalinventory.ListRegionalInventoriesResponse()) + return_value = regionalinventory.ListRegionalInventoriesResponse.to_json( + regionalinventory.ListRegionalInventoriesResponse() + ) req.return_value.content = return_value request = regionalinventory.ListRegionalInventoriesRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = regionalinventory.ListRegionalInventoriesResponse() - post_with_metadata.return_value = regionalinventory.ListRegionalInventoriesResponse(), metadata + post_with_metadata.return_value = ( + regionalinventory.ListRegionalInventoriesResponse(), + metadata, + ) - client.list_regional_inventories(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.list_regional_inventories( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_insert_regional_inventory_rest_bad_request(request_type=regionalinventory.InsertRegionalInventoryRequest): +def test_insert_regional_inventory_rest_bad_request( + request_type=regionalinventory.InsertRegionalInventoryRequest, +): client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/products/sample2'} + request_init = {"parent": "accounts/sample1/products/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() @@ -2720,25 +3356,42 @@ def test_insert_regional_inventory_rest_bad_request(request_type=regionalinvento client.insert_regional_inventory(request) -@pytest.mark.parametrize("request_type", [ - regionalinventory.InsertRegionalInventoryRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + regionalinventory.InsertRegionalInventoryRequest, + dict, + ], +) def test_insert_regional_inventory_rest_call_success(request_type): client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/products/sample2'} - request_init["regional_inventory"] = {'name': 'name_value', 'account': 749, 'region': 'region_value', 'regional_inventory_attributes': {'price': {'amount_micros': 1408, 'currency_code': 'currency_code_value'}, 'sale_price': {}, 'sale_price_effective_date': {'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}}, 'availability': 1}} + request_init = {"parent": "accounts/sample1/products/sample2"} + request_init["regional_inventory"] = { + "name": "name_value", + "account": 749, + "region": "region_value", + "regional_inventory_attributes": { + "price": {"amount_micros": 1408, "currency_code": "currency_code_value"}, + "sale_price": {}, + "sale_price_effective_date": { + "start_time": {"seconds": 751, "nanos": 543}, + "end_time": {}, + }, + "availability": 1, + }, + } # 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 = regionalinventory.InsertRegionalInventoryRequest.meta.fields["regional_inventory"] + test_field = regionalinventory.InsertRegionalInventoryRequest.meta.fields[ + "regional_inventory" + ] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -2752,7 +3405,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 @@ -2766,7 +3419,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["regional_inventory"].items(): # pragma: NO COVER + for field, value in request_init["regional_inventory"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -2781,12 +3434,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") @@ -2799,12 +3456,12 @@ 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 = regionalinventory.RegionalInventory( - name='name_value', - account=749, - region='region_value', + name="name_value", + account=749, + region="region_value", ) # Wrap the value into a proper Response obj @@ -2814,35 +3471,48 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = regionalinventory.RegionalInventory.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.insert_regional_inventory(request) # Establish that the response is the type that we expect. assert isinstance(response, regionalinventory.RegionalInventory) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.account == 749 - assert response.region == 'region_value' + assert response.region == "region_value" @pytest.mark.parametrize("null_interceptor", [True, False]) def test_insert_regional_inventory_rest_interceptors(null_interceptor): transport = transports.RegionalInventoryServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegionalInventoryServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.RegionalInventoryServiceRestInterceptor(), + ) client = RegionalInventoryServiceClient(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.RegionalInventoryServiceRestInterceptor, "post_insert_regional_inventory") as post, \ - mock.patch.object(transports.RegionalInventoryServiceRestInterceptor, "post_insert_regional_inventory_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.RegionalInventoryServiceRestInterceptor, "pre_insert_regional_inventory") 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.RegionalInventoryServiceRestInterceptor, + "post_insert_regional_inventory", + ) as post, mock.patch.object( + transports.RegionalInventoryServiceRestInterceptor, + "post_insert_regional_inventory_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.RegionalInventoryServiceRestInterceptor, + "pre_insert_regional_inventory", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = regionalinventory.InsertRegionalInventoryRequest.pb(regionalinventory.InsertRegionalInventoryRequest()) + pb_message = regionalinventory.InsertRegionalInventoryRequest.pb( + regionalinventory.InsertRegionalInventoryRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2853,39 +3523,55 @@ def test_insert_regional_inventory_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 = regionalinventory.RegionalInventory.to_json(regionalinventory.RegionalInventory()) + return_value = regionalinventory.RegionalInventory.to_json( + regionalinventory.RegionalInventory() + ) req.return_value.content = return_value request = regionalinventory.InsertRegionalInventoryRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = regionalinventory.RegionalInventory() - post_with_metadata.return_value = regionalinventory.RegionalInventory(), metadata + post_with_metadata.return_value = ( + regionalinventory.RegionalInventory(), + metadata, + ) - client.insert_regional_inventory(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.insert_regional_inventory( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_delete_regional_inventory_rest_bad_request(request_type=regionalinventory.DeleteRegionalInventoryRequest): +def test_delete_regional_inventory_rest_bad_request( + request_type=regionalinventory.DeleteRegionalInventoryRequest, +): client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/products/sample2/regionalInventories/sample3'} + request_init = { + "name": "accounts/sample1/products/sample2/regionalInventories/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() @@ -2894,30 +3580,34 @@ def test_delete_regional_inventory_rest_bad_request(request_type=regionalinvento client.delete_regional_inventory(request) -@pytest.mark.parametrize("request_type", [ - regionalinventory.DeleteRegionalInventoryRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + regionalinventory.DeleteRegionalInventoryRequest, + dict, + ], +) def test_delete_regional_inventory_rest_call_success(request_type): client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/products/sample2/regionalInventories/sample3'} + request_init = { + "name": "accounts/sample1/products/sample2/regionalInventories/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_regional_inventory(request) @@ -2930,15 +3620,24 @@ def test_delete_regional_inventory_rest_call_success(request_type): def test_delete_regional_inventory_rest_interceptors(null_interceptor): transport = transports.RegionalInventoryServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegionalInventoryServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.RegionalInventoryServiceRestInterceptor(), + ) client = RegionalInventoryServiceClient(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.RegionalInventoryServiceRestInterceptor, "pre_delete_regional_inventory") 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.RegionalInventoryServiceRestInterceptor, + "pre_delete_regional_inventory", + ) as pre: pre.assert_not_called() - pb_message = regionalinventory.DeleteRegionalInventoryRequest.pb(regionalinventory.DeleteRegionalInventoryRequest()) + pb_message = regionalinventory.DeleteRegionalInventoryRequest.pb( + regionalinventory.DeleteRegionalInventoryRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2951,20 +3650,26 @@ def test_delete_regional_inventory_rest_interceptors(null_interceptor): req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = regionalinventory.DeleteRegionalInventoryRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - client.delete_regional_inventory(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.delete_regional_inventory( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() + def test_initialize_client_w_rest(): client = RegionalInventoryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None @@ -2979,8 +3684,8 @@ def test_list_regional_inventories_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_regional_inventories), - '__call__') as call: + type(client.transport.list_regional_inventories), "__call__" + ) as call: client.list_regional_inventories(request=None) # Establish that the underlying stub method was called. @@ -3001,8 +3706,8 @@ def test_insert_regional_inventory_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.insert_regional_inventory), - '__call__') as call: + type(client.transport.insert_regional_inventory), "__call__" + ) as call: client.insert_regional_inventory(request=None) # Establish that the underlying stub method was called. @@ -3023,8 +3728,8 @@ def test_delete_regional_inventory_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_regional_inventory), - '__call__') as call: + type(client.transport.delete_regional_inventory), "__call__" + ) as call: client.delete_regional_inventory(request=None) # Establish that the underlying stub method was called. @@ -3045,18 +3750,21 @@ def test_transport_grpc_default(): transports.RegionalInventoryServiceGrpcTransport, ) + def test_regional_inventory_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.RegionalInventoryServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_regional_inventory_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.shopping.merchant_inventories_v1.services.regional_inventory_service.transports.RegionalInventoryServiceTransport.__init__') as Transport: + with mock.patch( + "google.shopping.merchant_inventories_v1.services.regional_inventory_service.transports.RegionalInventoryServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.RegionalInventoryServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -3065,9 +3773,9 @@ def test_regional_inventory_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'list_regional_inventories', - 'insert_regional_inventory', - 'delete_regional_inventory', + "list_regional_inventories", + "insert_regional_inventory", + "delete_regional_inventory", ) for method in methods: with pytest.raises(NotImplementedError): @@ -3078,7 +3786,7 @@ def test_regional_inventory_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -3087,25 +3795,30 @@ def test_regional_inventory_service_base_transport(): def test_regional_inventory_service_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.shopping.merchant_inventories_v1.services.regional_inventory_service.transports.RegionalInventoryServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.shopping.merchant_inventories_v1.services.regional_inventory_service.transports.RegionalInventoryServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionalInventoryServiceTransport( 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/content', -), + default_scopes=("https://www.googleapis.com/auth/content",), quota_project_id="octopus", ) def test_regional_inventory_service_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.shopping.merchant_inventories_v1.services.regional_inventory_service.transports.RegionalInventoryServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.shopping.merchant_inventories_v1.services.regional_inventory_service.transports.RegionalInventoryServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionalInventoryServiceTransport() @@ -3114,14 +3827,12 @@ def test_regional_inventory_service_base_transport_with_adc(): def test_regional_inventory_service_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) RegionalInventoryServiceClient() adc.assert_called_once_with( scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/content', -), + default_scopes=("https://www.googleapis.com/auth/content",), quota_project_id=None, ) @@ -3136,12 +3847,12 @@ def test_regional_inventory_service_auth_adc(): def test_regional_inventory_service_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: + 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/content',), + default_scopes=("https://www.googleapis.com/auth/content",), quota_project_id="octopus", ) @@ -3155,48 +3866,47 @@ def test_regional_inventory_service_transport_auth_adc(transport_class): ], ) def test_regional_inventory_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] + 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.RegionalInventoryServiceGrpcTransport, grpc_helpers), - (transports.RegionalInventoryServiceGrpcAsyncIOTransport, grpc_helpers_async) + (transports.RegionalInventoryServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -def test_regional_inventory_service_transport_create_channel(transport_class, grpc_helpers): +def test_regional_inventory_service_transport_create_channel( + transport_class, grpc_helpers +): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + 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( "merchantapi.googleapis.com:443", credentials=creds, credentials_file=None, quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/content', -), + default_scopes=("https://www.googleapis.com/auth/content",), scopes=["1", "2"], default_host="merchantapi.googleapis.com", ssl_credentials=None, @@ -3207,9 +3917,15 @@ def test_regional_inventory_service_transport_create_channel(transport_class, gr ) -@pytest.mark.parametrize("transport_class", [transports.RegionalInventoryServiceGrpcTransport, transports.RegionalInventoryServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.RegionalInventoryServiceGrpcTransport, + transports.RegionalInventoryServiceGrpcAsyncIOTransport, + ], +) def test_regional_inventory_service_grpc_transport_client_cert_source_for_mtls( - transport_class + transport_class, ): cred = ga_credentials.AnonymousCredentials() @@ -3219,7 +3935,7 @@ def test_regional_inventory_service_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", @@ -3240,61 +3956,77 @@ def test_regional_inventory_service_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_regional_inventory_service_http_transport_client_cert_source_for_mtls(): cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.RegionalInventoryServiceRestTransport ( - 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.RegionalInventoryServiceRestTransport( + 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_regional_inventory_service_host_no_port(transport_name): client = RegionalInventoryServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='merchantapi.googleapis.com'), - transport=transport_name, + client_options=client_options.ClientOptions( + api_endpoint="merchantapi.googleapis.com" + ), + transport=transport_name, ) assert client.transport._host == ( - 'merchantapi.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://merchantapi.googleapis.com' + "merchantapi.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://merchantapi.googleapis.com" ) -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) def test_regional_inventory_service_host_with_port(transport_name): client = RegionalInventoryServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='merchantapi.googleapis.com:8000'), + client_options=client_options.ClientOptions( + api_endpoint="merchantapi.googleapis.com:8000" + ), transport=transport_name, ) assert client.transport._host == ( - 'merchantapi.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://merchantapi.googleapis.com:8000' + "merchantapi.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://merchantapi.googleapis.com:8000" ) -@pytest.mark.parametrize("transport_name", [ - "rest", -]) + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) def test_regional_inventory_service_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -3315,8 +4047,10 @@ def test_regional_inventory_service_client_transport_session_collision(transport session1 = client1.transport.delete_regional_inventory._session session2 = client2.transport.delete_regional_inventory._session assert session1 != session2 + + def test_regional_inventory_service_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.RegionalInventoryServiceGrpcTransport( @@ -3329,7 +4063,7 @@ def test_regional_inventory_service_grpc_transport_channel(): def test_regional_inventory_service_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.RegionalInventoryServiceGrpcAsyncIOTransport( @@ -3343,12 +4077,22 @@ def test_regional_inventory_service_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.parametrize("transport_class", [transports.RegionalInventoryServiceGrpcTransport, transports.RegionalInventoryServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.RegionalInventoryServiceGrpcTransport, + transports.RegionalInventoryServiceGrpcAsyncIOTransport, + ], +) def test_regional_inventory_service_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 @@ -3357,7 +4101,7 @@ def test_regional_inventory_service_transport_channel_mtls_with_client_cert_sour 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", @@ -3387,17 +4131,23 @@ def test_regional_inventory_service_transport_channel_mtls_with_client_cert_sour # 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.RegionalInventoryServiceGrpcTransport, transports.RegionalInventoryServiceGrpcAsyncIOTransport]) -def test_regional_inventory_service_transport_channel_mtls_with_adc( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.RegionalInventoryServiceGrpcTransport, + transports.RegionalInventoryServiceGrpcAsyncIOTransport, + ], +) +def test_regional_inventory_service_transport_channel_mtls_with_adc(transport_class): mock_ssl_cred = mock.Mock() with mock.patch.multiple( "google.auth.transport.grpc.SslCredentials", __init__=mock.Mock(return_value=None), ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + 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() @@ -3429,8 +4179,16 @@ def test_regional_inventory_path(): account = "squid" product = "clam" region = "whelk" - expected = "accounts/{account}/products/{product}/regionalInventories/{region}".format(account=account, product=product, region=region, ) - actual = RegionalInventoryServiceClient.regional_inventory_path(account, product, region) + expected = ( + "accounts/{account}/products/{product}/regionalInventories/{region}".format( + account=account, + product=product, + region=region, + ) + ) + actual = RegionalInventoryServiceClient.regional_inventory_path( + account, product, region + ) assert expected == actual @@ -3446,9 +4204,12 @@ def test_parse_regional_inventory_path(): actual = RegionalInventoryServiceClient.parse_regional_inventory_path(path) assert expected == actual + def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) actual = RegionalInventoryServiceClient.common_billing_account_path(billing_account) assert expected == actual @@ -3463,9 +4224,12 @@ def test_parse_common_billing_account_path(): actual = RegionalInventoryServiceClient.parse_common_billing_account_path(path) assert expected == actual + def test_common_folder_path(): folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) + expected = "folders/{folder}".format( + folder=folder, + ) actual = RegionalInventoryServiceClient.common_folder_path(folder) assert expected == actual @@ -3480,9 +4244,12 @@ def test_parse_common_folder_path(): actual = RegionalInventoryServiceClient.parse_common_folder_path(path) assert expected == actual + def test_common_organization_path(): organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) + expected = "organizations/{organization}".format( + organization=organization, + ) actual = RegionalInventoryServiceClient.common_organization_path(organization) assert expected == actual @@ -3497,9 +4264,12 @@ def test_parse_common_organization_path(): actual = RegionalInventoryServiceClient.parse_common_organization_path(path) assert expected == actual + def test_common_project_path(): project = "squid" - expected = "projects/{project}".format(project=project, ) + expected = "projects/{project}".format( + project=project, + ) actual = RegionalInventoryServiceClient.common_project_path(project) assert expected == actual @@ -3514,10 +4284,14 @@ def test_parse_common_project_path(): actual = RegionalInventoryServiceClient.parse_common_project_path(path) assert expected == actual + def test_common_location_path(): project = "whelk" location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) actual = RegionalInventoryServiceClient.common_location_path(project, location) assert expected == actual @@ -3537,14 +4311,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.RegionalInventoryServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.RegionalInventoryServiceTransport, "_prep_wrapped_messages" + ) as prep: client = RegionalInventoryServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.RegionalInventoryServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.RegionalInventoryServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = RegionalInventoryServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -3555,10 +4333,11 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = RegionalInventoryServiceClient( - 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() @@ -3567,10 +4346,11 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = RegionalInventoryServiceAsyncClient( - 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() @@ -3578,10 +4358,11 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = RegionalInventoryServiceClient( - 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() @@ -3589,13 +4370,12 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = RegionalInventoryServiceClient( - 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: @@ -3604,10 +4384,20 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (RegionalInventoryServiceClient, transports.RegionalInventoryServiceGrpcTransport), - (RegionalInventoryServiceAsyncClient, transports.RegionalInventoryServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + ( + RegionalInventoryServiceClient, + transports.RegionalInventoryServiceGrpcTransport, + ), + ( + RegionalInventoryServiceAsyncClient, + transports.RegionalInventoryServiceGrpcAsyncIOTransport, + ), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -3622,7 +4412,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,